Cheat Sheet
- Linux: /linux/
- CLI: /linux/cli/
- locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/
- make: /linux/cli/make/
- awk: /linux/cli/awk/
- find: /linux/cli/find/
- grep: /linux/cli/grep/
- pgrep: /linux/cli/pgrep/
- ps: /linux/cli/ps/
- pstree: /linux/cli/pstree/
- trap: /linux/cli/trap/
- xargs: /linux/cli/xargs/
- Shell: /linux/shell/
- BASH_SOURCE: /linux/shell/bash-source/
- Redirection: /linux/shell/redirection/
- Special Variables: /linux/shell/special-variables/
- Scripting Tips: /linux/shell/script-tips/
- set -o vi: /linux/shell/bash-vi-mode/
- Shell Processing Order: /linux/shell/process-order/
- What are Interactive and Login Shells?: /linux/shell/interactive-login/
- Double Quote Expansion: /linux/shell/shell-expansion/
- System Programming: /linux/system-programming/
- File I/O: /linux/system-programming/file-io/
- Process: /linux/system-programming/process/
- Shared Libraries: /linux/system-programming/shared-libraries/
- Kernel: /linux/kernel/
- Go: /programming/go/
- Concurrency: /programming/go/concurrency/
- CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/
- Channel: /programming/go/concurrency/channel/
- Select: /programming/go/concurrency/select/
- sync: /programming/go/concurrency/sync/
- Concurrency Patterns: /programming/go/concurrency/patterns/
- Goroutines and the Go Runtime: /programming/go/concurrency/runtime/
- Standard Library: /programming/go/std/
- os: /programming/go/std/os/
- context: /programming/go/std/context/
- io: /programming/go/std/io/
- json: /programming/go/std/json/
- net/http: /programming/go/std/net-http/
- slog: /programming/go/std/slog/
- testing: /programming/go/std/testing/
- time: /programming/go/std/time/
- Ellipsis (...): /programming/go/ellipsis/
- error: /programming/go/error/
- Function: /programming/go/function/
- Go Tool: /programming/go/tool/
- Interface: /programming/go/interface/
- Map: /programming/go/map/
- Package and Module: /programming/go/package-module/
- Pointer: /programming/go/pointer/
- Slice: /programming/go/slice/
- String: /programming/go/string/
- Switch: /programming/go/switch/
- Comparison: /programming/go/comparison/
- defaultdict: /programming/python/collections/defaultdict/
- heapq: /programming/python/collections/heapq/
- @cache: /programming/python/cache/
- abc: /programming/python/abc/
- bisect: /programming/python/bisect/
- Type Hints: /programming/python/type-hints/
- Passing Mechanism: /programming/python/passing-mechanism/
- uv: /programming/python/uv/
- *args and **kwargs: /programming/python/args-kwargs/
- re: /programming/python/re/
- C: /programming/c/
- Pointers and Arrays: /programming/c/pointer/
- Syntax Basics: /programming/c/syntax-basics/
- static: /programming/c/static/
- Bit Manipulation: /programming/c/bit-manipulation/
- C vs C++: /programming/c/c-vs-cpp/
- stdatomic: /programming/c/stdatomic/
- C++: /programming/cpp/
- RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/
- Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/
- Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/
- C++ Keywords Reference: /programming/cpp/keywords/
- C++ Primer: /programming/cpp/primer/
- Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/
- Expressions: /programming/cpp/primer/expressions/
- Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/
- Statements: /programming/cpp/primer/statements/
- Functions: /programming/cpp/primer/functions/
- Classes: /programming/cpp/primer/classes/
- The IO Library: /programming/cpp/primer/io-library/
- STL: /programming/cpp/primer/stl/
- Lambda Expressions: /programming/cpp/primer/lambda/
- Smart Pointers: /programming/cpp/primer/smart-pointers/
- Copy Control: /programming/cpp/primer/copy-control/
- Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/
- Object-Oriented Programming (OOP): /programming/cpp/primer/oop/
- Templates and Generic Programming: /programming/cpp/primer/templates/
- Namespaces: /programming/cpp/primer/namespaces/
- Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/
- Advanced: /programming/cpp/advanced/
- Error Handling: /programming/cpp/advanced/error-handling/
- Concurrency & Threading: /programming/cpp/advanced/concurrency/
- Unit Testing: /programming/cpp/advanced/unit-testing/
- Comparison: /programming/comparison/
- Kubernetes: /cloud-devops/kubernetes/
- Fleet: /cloud-devops/kubernetes/gke/fleet/
- Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/
- API Extension: /cloud-devops/kubernetes/api-extension/
- Concept: /cloud-devops/kubernetes/kueue/concept/
- DRA: /cloud-devops/kubernetes/dra/
- Secret Manager: /cloud-devops/terraform/google-secret-manager/
- Knowledge: /network/knowledge/
- PDU: /network/knowledge/osi-model/
- curl: /network/cli/curl/
- Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/
- Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/
- Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/
- Regular Expression: /cs/regular-expression/
- Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/
- Driver and Runtime: /ai-ml/gpu/driver-and-runtime/
- Serving: /ai-ml/serving/
- Dotfiles: /dotfiles/
- Git: /dotfiles/git/
- Cheat Sheet: /dotfiles/git/cheat-sheet/
- revisions: /dotfiles/git/revisions/
- Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/
- checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/
- rebase: /dotfiles/git/rebase/
- Branching and Merging: /dotfiles/git/branching-merging/
- Vim: /dotfiles/vim/
- Plugin: /dotfiles/vim/plugin/
- auto-pairs: /dotfiles/vim/plugin/auto-pairs/
- vim-commentary: /dotfiles/vim/plugin/vim-commentary/
- vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/
- vim-surround: /dotfiles/vim/plugin/vim-surround/
- Marks: /dotfiles/vim/tips/marks/
- vimrc: /dotfiles/vim/vimrc/
- lf: /dotfiles/lf/
# Copy Control
Summary based on *C++ Primer, 5th ed.* Chapter 13: Copy Control, covering the five special member functions that govern object initialization, assignment, movement, and destruction, along with essential control keywords. For a dedicated deep dive into Move Semantics, `T&&`, `std::move`, and move constructor/assignment implementation, see [Copy Elision & Move Semantics]({{< relref "/programming/cpp/copy-elision-and-move-semantics.md" >}}).
## 1. The Five Copy-Control Special Member Functions
In C++, **five special member functions** govern an object's lifecycle and resource copying/moving across three lifecycle stages:
- **Initialization — Constructor:** Constructs and initializes a **brand-new object** that did not exist yet.
- **Assignment — Assignment Operator:** Overwrites an **already-constructed live object**.
- **Destruction — Destructor:** Releases owned resources when an object's lifetime ends — the core mechanism of [RAII]({{< relref "/programming/cpp/raii.md" >}}).
| Special Member Function | Signature | When Invoked & Heap Resource Behavior |
| :--- | :--- | :--- |
| **Copy Constructor** | `CLASS(const CLASS&);` | Invoked when **initializing a new object** from an existing lvalue; **allocates new heap memory for a deep copy**. |
| **Move Constructor** | `CLASS(CLASS&&) noexcept;` | Invoked when **initializing a new object** from an rvalue temporary; steals the source's resource pointer **with zero new heap allocations**. |
| **Copy Assignment** | `CLASS& operator=(const CLASS&);` | Invoked when assigning an lvalue to an **already-constructed object**; copies into new heap memory before freeing old owned resources. |
| **Move Assignment** | `CLASS& operator=(CLASS&&) noexcept;` | Invoked when assigning an rvalue to an **already-constructed object**; frees old owned resources and steals the source's pointer **with zero new heap allocations**. |
| **Destructor** | `~CLASS();` | Automatically invoked when an object leaves scope to free owned heap resources. |
- **Why Does `operator=` Return a Reference `CLASS&`?**
- Because the left-hand object `*this` already exists in memory, `return *this;` returns **the original object itself without creating an unnecessary temporary copy `CLASS`**. This avoids extra copy overhead and also works for move-only types whose copy constructor is deleted.
```cpp
class Foo {
public:
Foo(); // default constructor
Foo(const Foo&); // copy constructor: initializes new object via deep copy
Foo(Foo&&) noexcept; // move constructor: initializes new object by stealing pointer
Foo& operator=(const Foo&); // copy assignment: copy-assigns to existing object
Foo& operator=(Foo&&) noexcept; // move assignment: move-assigns to existing object
~Foo(); // destructor: releases resources when object ceases to exist
};
class NoCopy {
NoCopy() = default; // use the synthesized default constructor
NoCopy(const NoCopy&) = delete; // no copy constructor
NoCopy& operator=(const NoCopy&) = delete; // no copy assignment
~NoCopy() = default; // use the synthesized destructor
// other members
};
```
### Important: `=` in a Declaration Is Initialization (Constructor), Not Assignment!
Even when the `=` token appears, if a statement is **declaring a new variable**, it invokes the **copy/move constructor**, NOT `operator=`:
```cpp
Foo a; // Default constructor: initializes new object a
Foo b(a); // Copy constructor: direct initialization of new object b
Foo c = a; // Copy constructor: '=' in a declaration is copy initialization of new object c, NOT operator=!
Foo d = std::move(a); // Move constructor: initializes new object d, NOT move assignment!
c = b; // Copy assignment: overwrites already-existing object c
c = std::move(d); // Move assignment: move-assigns into already-existing object c
```
---
## 2. Essential Keywords (`= default`, `= delete`, `noexcept`, `explicit`, `virtual`)
For a comprehensive summary of the keywords that control special member functions and constructors — `= default`, `= delete`, `noexcept`, `explicit`, `virtual`, and more — see **[C++ Keywords Reference]({{< relref "/programming/cpp/keywords.md" >}})**.
---
## 3. Deep Copy and Self-Assignment Safety
When a class manages dynamic memory directly, enforce these two rules when implementing copy construction and copy assignment:
1. **Copy Constructor Parameter Must Be a Reference `const CLASS&`:** Passing by value `CLASS(CLASS p)` would require calling the copy constructor to initialize `p`, causing infinite recursion.
2. **Copy Assignment `operator=` Must Be Safe Against Self-Assignment `a = a`:** Deleting the left-hand object's existing memory first would destroy the source data when `a = a`. Always **copy the right-hand data into a new heap allocation BEFORE deleting existing memory**.
```cpp
class HasPtr {
private:
std::string *ps;
int i;
public:
HasPtr(const std::string &s = std::string())
: ps(new std::string(s)), i(0) {}
// Copy constructor: allocates new heap memory and initializes via deep copy
HasPtr(const HasPtr &orig)
: ps(new std::string(*orig.ps)), i(orig.i) {}
// Copy assignment: copies into new memory BEFORE deleting old memory for self-assignment safety!
HasPtr& operator=(const HasPtr &rhs) {
auto newp = new std::string(*rhs.ps); // 1. Copy rhs first — safe even if rhs is *this
delete ps; // 2. Free old heap memory owned by *this
ps = newp; // 3. Bind new pointer
i = rhs.i;
return *this;
}
// Destructor: frees heap memory when the object ceases to exist
~HasPtr() { delete ps; }
};
```
---
## 4. The Rule of Three / Five / Zero
| Rule | Target Member Functions | Core Principle |
| :--- | :--- | :--- |
| **Rule of Three**
C++98 | **1. Destructor (`~CLASS`)**
**2. Copy Constructor**
**3. Copy Assignment** | If a class requires a custom **destructor** such as calling `delete`, the compiler's default shallow copy will cause a Double Free bug, so it **must also define both a copy constructor and copy assignment operator**. |
| **Rule of Five**
C++11~ | The 3 from Rule of Three
**+ 4. Move Constructor**
**+ 5. Move Assignment** | Expanded in C++11 with [Copy Elision & Move Semantics]({{< relref "/programming/cpp/copy-elision-and-move-semantics.md" >}}). If you define any one of these 5 special member functions, you should **define or `= delete` all 5 as a unit**. |
| **Rule of Zero**
Modern C++ Best Practice | **0** custom functions | By using standard [RAII]({{< relref "/programming/cpp/raii.md" >}}) members such as `std::string`, `std::vector`, `unique_ptr`, and `shared_ptr` instead of raw pointers `T*`, you write none of the 5 functions yourself and rely safely on the compiler-synthesized defaults. |
> **See Also: Ref-qualified Member Functions `&` / `&&` & Copy/Move Guidelines:**
> - For restricting or overloading member functions based on whether the receiver `*this` is an lvalue or an rvalue, see **[Copy Elision & Move Semantics: Ref-qualified Member Functions]({{< relref "/programming/cpp/copy-elision-and-move-semantics.md#6-ref-qualified-member-functions" >}})**.
> - For how Copy Elision and Move Semantics eliminate copies whenever a value never has two live names simultaneously, see **[Copy Elision & Move Semantics: Practical Rules of Thumb for Avoiding Unnecessary Copies]({{< relref "/programming/cpp/copy-elision-and-move-semantics.md#2-practical-rules-of-thumb-for-avoiding-unnecessary-copies-copy-elision--move" >}})**.