Post

Copy Optimization

Copy Optimization

Copy Optimization in C++: Pointer, Swap, and Move Semantics


Prerequisites


1. Why Copy Matters

Avoid unnecessary copies in performance-critical code.

Copying objects can be expensive:

  • Memory allocation
  • Deep copy of data
  • Cache inefficiency

Minimize copying by:

  1. Managing via pointer/reference
  2. Building internally and swapping
  3. Using move semantics (rvalue)
StrategyUse Case
Reference (const&)Read-only access
PointerOptional / nullable
SwapReplace large object
Move (std::move)Transfer ownership

2. Pointer / Reference Management

✔ Avoid Copy
1
void process(const std::vector<int>& data);
  • No copy
  • Only reference passed
✔ Pointer
1
void process(const std::vector<int>* data);
  • Same idea → no copy
  • Use when nullable or explicit ownership needed

3. Build Then Swap

❌ Direct Copy
1
2
std::vector<int> v;
v = create_large_vector();  // copy or move
✔ Efficient Swap
1
2
std::vector<int> temp = create_large_vector();
v.swap(temp);
  • Constant-time swap (pointer exchange)
  • No deep copy

4. Move Semantics (Rvalue)

✔ Move Instead of Copy
1
std::vector<int> v = create_large_vector();

Uses move (or copy elision)

✔ Explicit Move
1
2
std::vector<int> v;
v = std::move(temp);
  • Transfers ownership
  • Avoids deep copy
Rvalue Reference
1
void process(std::vector<int>&& data);
  • Accepts temporary object
  • Enables move semantics

5. Practice

❌ Inefficient
1
2
3
4
5
6
std::vector<int> getData() 
{
    std::vector<int> v;
    // fill
    return v;  // might copy (pre-C++17)
}
✔ Efficient (C++17)
1
2
3
4
5
6
std::vector<int> getData() 
{
    std::vector<int> v;
    // fill
    return v;  // copy elision
}
✔ Replace Pattern
1
2
3
4
5
6
void update(std::vector<int>& v) 
{
    std::vector<int> temp;
    // fill temp
    v.swap(temp);
}
✔ Return Value Optimization (RVO)
1
2
3
4
std::vector<int> create() 
{
    return std::vector<int>(100);
}

No copy, no move (C++17 guaranteed)

✔ DO
  • Use const T& for input
  • Use std::move when transferring ownership
  • Use swap() for replacing large containers
  • Rely on copy elision (C++17)
❌ DON’T
  • Copy large objects unnecessarily
  • Overuse std::move
  • Ignore object lifetime
This post is licensed under CC BY 4.0 by the author.