Module 4 · Your own types
4.3Copy and move
Say what copying your class means, hand heap memory from one object to another with a move instead of copying it, and learn the rule of five and why std::vector needs noexcept moves.
On this page
- Key terms
- In 30 seconds
- Copying: two special member functions
- Copying an object that owns memory
- Moving: take the memory instead of copying it
- Copy or move? lvalues and rvalues
- std::move doesn’t move anything
- The moved-from state
- = default and = delete
- The rule of five
- The rule of zero, again
- noexcept moves and std::vector
- Which one should I use?
- Under the hood
- Common pitfalls
- return std::move(local)
- Using an object after moving from it
- std::move on a const object copies
- Try it yourself
Key terms
- copy constructor and copy assignment
T(const T&)builds a new object as a copy of an existing one (T b = a;, or passingaby value).operator=(const T&)makes an object that already exists a copy of another (b = a;).- deep copy
- A copy of what a pointer points to: the new object gets its own heap block with the same values. Copying only the pointer is a shallow copy.
- move constructor and move assignment
T(T&&)andoperator=(T&&): build or overwrite an object by taking the contents of one nobody will use again, instead of copying them.- lvalue and rvalue
- An lvalue names an object you can use again, like a variable
a. An rvalue is a temporary with no name, or an object passed throughstd::move; its contents may be taken. std::move- A cast that turns an lvalue into an rvalue, so a move constructor or move assignment can be chosen. It doesn't move anything by itself.
- moved-from state
- What's left of an object after a move. The standard library promises only that it's valid: you can assign it a new value or let it be destroyed.
= defaultand= delete- Written instead of a function body:
= defaultasks the compiler to write the function member by member;= deleteforbids it, so code that calls it doesn't compile. - rule of five
- If a class declares a destructor or any copy or move function, it should declare all five, writing each one, or marking it
= defaultor= delete. noexcept- A promise that a function never throws an exception. When a
std::vectorgrows, it moves elements whose move constructor makes this promise, and copies the others if it can. - copy elision
- The compiler building a returned object directly in the caller's variable, so there's no copy or move at all.
Assigning one int to another copies the number, and that’s the end of it. A class that owns heap memory needs more care. In Dynamic memory and RAII, copying a Buffer copied its pointer, and both copies freed the same floats. This lesson shows how a class says what copying means, how it can hand its heap memory to another object instead of copying it, and why most classes should let the compiler write all of this for them.
In 30 seconds
- The copy constructor builds a new object from an existing one, and copy assignment overwrites an object that already exists. A class that owns memory must copy the memory, not the pointer.
- A move takes the contents of an object that won’t be used again, usually leaving it empty. For a class that owns a heap block, that means copying one pointer instead of every element.
- C++ moves from temporaries, from objects you pass to
std::move, and from a local variable you return. It copies other named objects. - Prefer members that already copy and move correctly, like
std::vector, and write none of these functions (the rule of zero). If you write one, declare all five (the rule of five), and mark the movesnoexcept.
Copying: two special member functions
When you copy an object of your own class, C++ calls one of two special member functions, the functions Constructors listed that the compiler writes if you don’t. You can write them yourself. This Tracer writes both and prints a line from each, so you can see when they run:
#include <print>
#include <string>
struct Tracer {
std::string name;
explicit Tracer(const std::string& n) : name(n) {}
Tracer(const Tracer& other) : name(other.name) {
std::println("copy constructor: a copy of {}", name);
}
Tracer& operator=(const Tracer& other) {
std::println("copy assignment: {} becomes {}", name, other.name);
name = other.name;
return *this;
}
};
void show(Tracer t) {
std::println("show {}", t.name);
}
int main() {
Tracer a("a");
Tracer b = a; // b is new: copy constructor
Tracer c("c");
c = a; // c already exists: copy assignment
show(a); // the parameter t is new: copy constructor
}Output
copy constructor: a copy of a copy assignment: c becomes a copy constructor: a copy of a show a
The copy constructor Tracer(const Tracer& other) builds a new object, so it also runs when you pass by value: the parameter t is a new object. Copy assignment is a member function named operator=: c = a calls c.operator=(a), which overwrites c. It returns *this, a reference to c itself, as the built-in = does. Operators and comparisons covers writing operators in general.
Key ideaAn = in a declaration isn't assignment
Tracer b = a; creates b, so it calls the copy constructor. Only = on an object that already exists, like c = a;, calls copy assignment.
If you don’t write them, the compiler writes both: they copy each member in turn. For Tracer, that copies the std::string, which is exactly what these versions do, minus the printing.
Copying an object that owns memory
Copying member by member goes wrong when a member is a raw pointer that owns a heap block: you get a shallow copy. The new object holds the same address, and both destructors free it, the double free from Dynamic memory and RAII. A copy constructor that makes a deep copy gives the new object its own block, with the same values:
#include <algorithm>
#include <cstddef>
#include <print>
struct Buffer {
float* data;
std::size_t size;
explicit Buffer(std::size_t n) : data(new float[n]{}), size(n) {}
~Buffer() { delete[] data; }
Buffer(const Buffer& other)
: data(new float[other.size]), size(other.size) {
std::copy_n(other.data, size, data); // copy the floats themselves
}
};
int main() {
Buffer image(3);
Buffer backup = image; // a deep copy: new floats
image.data[0] = 0.5f;
std::println("image: {}, backup: {}", image.data[0], backup.data[0]);
}Output
image: 0.5, backup: 0
std::copy_n(other.data, size, data) copies size floats from other’s block into the new one. Changing image doesn’t touch backup, and each destructor frees its own block.
This Buffer isn’t finished: backup = image; would still use the compiler’s copy assignment and copy the pointer. The rule of five below completes it.
Moving: take the memory instead of copying it
A deep copy of a million floats allocates a new block and copies every float. That’s waste when the source is about to go away anyway. A move takes the source’s heap block instead: the new object copies the pointer, and the source gives up its claim by setting its own pointer to nullptr. The move constructor does this; its parameter type, Buffer&&, is explained in the next section. As with std::unique_ptr in Smart pointers, std::move(image) says that image’s contents may be taken.
#include <cstddef>
#include <print>
#include <utility>
struct Buffer {
float* data;
std::size_t size;
explicit Buffer(std::size_t n) : data(new float[n]{}), size(n) {}
~Buffer() { delete[] data; }
Buffer(Buffer&& other) noexcept : data(other.data), size(other.size) {
other.data = nullptr; // other no longer owns the floats
other.size = 0;
}
};
int main() {
Buffer image(3);
image.data[0] = 0.5f;
Buffer moved = std::move(image);
std::println("moved: {} floats, first {}", moved.size, moved.data[0]);
std::println("image: {} floats, empty: {}", image.size,
image.data == nullptr);
}Output
moved: 3 floats, first 0.5 image: 0 floats, empty: true
noexcept promises that the function never throws an exception; a later section shows why a move constructor should make that promise. At the end of main, both destructors still run. image’s calls delete[] on nullptr, which does nothing, so the floats are freed once, by moved.
The floats never moved. Only the Buffer itself, a pointer and a size (16 bytes on this platform), was copied, however many floats there are. That’s the whole point of a move: the heap block changes owner, and the source is left empty.
Copy or move? lvalues and rvalues
When a class has both a copy constructor and a move constructor, C++ picks one by asking whether the source can still be used afterwards:
- An lvalue is an expression that names an object you can use again, like a variable
a. Taking its contents would surprise the code that uses it later, so it’s copied. - An rvalue is a temporary with no name, like
Tracer("t")or the value a function returns, or an object you passed throughstd::move. Nobody can use it afterwards, or you’ve said nobody will, so its contents may be taken.
The move functions take an rvalue reference, Tracer&&: a reference that binds only to rvalues. The copy functions take const Tracer&, which binds to anything. For an rvalue, both fit, and C++ picks the better match: the move.
#include <print>
#include <string>
#include <utility>
struct Tracer {
std::string name;
explicit Tracer(const std::string& n) : name(n) {}
Tracer(const Tracer& other) : name(other.name) {
std::println("copy {}", name);
}
Tracer(Tracer&& other) noexcept : name(std::move(other.name)) {
std::println("move {}", name);
}
Tracer& operator=(const Tracer& other) {
name = other.name;
std::println("copy-assign {}", name);
return *this;
}
Tracer& operator=(Tracer&& other) noexcept {
name = std::move(other.name);
std::println("move-assign {}", name);
return *this;
}
};
int main() {
Tracer a("a");
Tracer b = a; // a is an lvalue: copy
Tracer c = std::move(a); // std::move(a) is an rvalue: move
b = Tracer("t"); // a temporary is an rvalue: move-assign
c = b; // b is an lvalue: copy-assign
}Output
copy a move a move-assign t copy-assign t
Inside the move functions, other has a name, so other and other.name are lvalues, even though other’s type is Tracer&&. That’s why they write std::move(other.name): without it, the string would be copied.
Later examples on this page reuse this Tracer. Its definition is hidden there to save space; the Run button includes it.
std::move doesn’t move anything
std::move(x) is a cast. It changes the expression x from an lvalue into an rvalue, and that’s all. The move happens only if the result goes somewhere with a move constructor or move assignment, like push_back, which has a version that takes T&&:
#include <print>
#include <string>
#include <utility>
#include <vector>
std::vector<std::string> ids;
std::string id = "read_001";
ids.push_back(id); // copy: id keeps its text
ids.push_back(std::move(id)); // move: id's text is taken
std::println("{} id=[{}]", ids, id);
id = "read_002"; // a moved-from string can be given a new value
ids.push_back(id);
std::println("{}", ids);Output
["read_001", "read_001"] id=[] ["read_001", "read_001", "read_002"]
Use std::move on a variable you’re finished with, at the point you hand it over.
The moved-from state
After a move, the source still exists, and its destructor still runs. The standard library promises only that a moved-from object is valid: you can destroy it or assign it a new value, as id = "read_002" does. It doesn’t promise what value it holds. With GCC’s standard library, a moved-from std::string is empty, as the output shows, but don’t write code that depends on that: treat std::move(x) as the last use of x until you give it a new value.
Your own classes decide their moved-from state. Buffer leaves nullptr and a size of 0, which its destructor handles. Whatever you choose, the destructor and assignment must still work on it.
= default and = delete
You can declare a special member function without writing its body:
= defaultasks the compiler to write it the usual way, member by member.= deleteforbids it. Code that would call it doesn’t compile.
Copying a camera frame of a million floats by accident is a slow bug that’s hard to spot. Deleting the copy functions makes Frame like std::unique_ptr: it can be moved, never copied:
#include <cstddef>
#include <vector>
struct Frame {
std::vector<float> pixels;
explicit Frame(std::size_t n) : pixels(n) {}
Frame(const Frame&) = delete;
Frame& operator=(const Frame&) = delete;
Frame(Frame&&) = default;
Frame& operator=(Frame&&) = default;
};
void process(Frame frame) {
frame.pixels[0] = 1.0f;
}
int main() {
Frame frame(1'000'000);
process(frame); // passing by value copies
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:20:12: error: use of deleted function ‘Frame::Frame(const Frame&)’
20 | process(frame); // passing by value copies
| ~~~~~~~^~~~~~~
main.cpp:8:5: note: declared here
8 | Frame(const Frame&) = delete;
| ^~~~~
main.cpp:20:12: note: use ‘-fdiagnostics-all-candidates’ to display considered candidates
20 | process(frame); // passing by value copies
| ~~~~~~~^~~~~~~
main.cpp:14:20: note: initializing argument 1 of ‘void process(Frame)’
14 | void process(Frame frame) {
| ~~~~~~^~~~~The moves are marked = default because declaring the copy functions, even as deleted, stops the compiler from writing the moves on its own. The fix is to say what you mean: process(std::move(frame)) moves the frame in if process should own it, and a Frame& parameter lets it work on the caller’s frame without a copy.
The rule of five
The compiler writes the copy and move functions only while you haven’t taken charge of them. It assumes a class that declares any of these needs special handling:
| You declare | The copy functions | The move functions |
|---|---|---|
| none of them | written by the compiler | written by the compiler |
| a destructor, or a copy function | the ones you didn’t declare are still written (an old rule, kept for old code) | not declared: moves become copies |
| a move function | deleted | only the ones you declare |
The middle row is the sneaky one. Here Sample has a destructor and nothing else, so it has no move constructor, and std::move quietly copies its Tracer:
#include <print>
#include <string>
#include <utility>
struct Sample {
Tracer reads{"reads"};
~Sample() { std::println("closing sample"); }
};
int main() {
Sample a;
Sample b = std::move(a); // no move constructor: copies
}Output
copy reads closing sample closing sample
So the rule of five: if a class declares a destructor, a copy constructor, a copy assignment, a move constructor or a move assignment, declare all five. Write each one, or mark it = default or = delete, so none of them is left to the rules in the table. Here is Buffer finished:
#include <algorithm>
#include <cstddef>
#include <print>
#include <utility>
struct Buffer {
float* data;
std::size_t size;
explicit Buffer(std::size_t n) : data(new float[n]{}), size(n) {}
~Buffer() { delete[] data; }
Buffer(const Buffer& other) : Buffer(other.size) {
std::copy_n(other.data, size, data);
}
Buffer& operator=(const Buffer& other) {
Buffer copy(other); // copy first, then swap the copy in
std::swap(data, copy.data);
std::swap(size, copy.size);
return *this; // copy's destructor frees the old floats
}
Buffer(Buffer&& other) noexcept
: data(std::exchange(other.data, nullptr)),
size(std::exchange(other.size, 0)) {}
Buffer& operator=(Buffer&& other) noexcept {
std::swap(data, other.data); // other gets the old floats
std::swap(size, other.size); // and frees them later
return *this;
}
};
int main() {
Buffer image(3);
image.data[0] = 0.5f;
Buffer backup(1);
backup = image; // copy assignment
Buffer moved(1);
moved = std::move(image); // move assignment
std::println("{} {} {}", backup.data[0], moved.data[0], image.size);
}Output
0.5 0.5 1
- The copy constructor reuses the main constructor (a delegating constructor, from Constructors) to get a zeroed block of the right size, then copies the floats into it.
std::exchange(other.data, nullptr)setsother.datatonullptrand returns the pointer it held: take it and leave the source empty, in one step.- Both assignments end with
*thisand the other object swapping contents withstd::swap. The old floats end up in an object that frees them when it’s destroyed. That also makesx = x;safe.
After the move assignment, image holds moved’s old block of 1 float, which is why image.size is 1. That’s a valid moved-from state: it isn’t empty, but nothing depends on it.
The rule of zero, again
Thirty lines of careful code, and every line is a chance for a bug. As Constructors said, the better plan is the rule of zero: own memory through members that already copy and move correctly, and declare none of the five. Give Buffer a std::vector<float> member instead of the raw pointer, like Image in that lesson, and the compiler’s versions copy, move and free the floats, with moves that are noexcept.
A std::unique_ptr member works the same way, but its copies are deleted, so the class can be moved but not copied, without a single = delete.
noexcept moves and std::vector
When a std::vector runs out of capacity, it allocates a bigger block and brings its elements over. It moves them only if their move constructor is noexcept (or if they can’t be copied at all). Here Tracer’s move constructor doesn’t promise that, and the vector copies (emplace_back, from vector, builds the new element in place):
#include <print>
#include <string>
#include <utility>
#include <vector>
struct Tracer {
std::string name;
explicit Tracer(const std::string& n) : name(n) {}
Tracer(const Tracer& other) : name(other.name) {
std::println("copy {}", name);
}
Tracer(Tracer&& other) : name(std::move(other.name)) {
std::println("move {}", name);
}
};
int main() {
std::vector<Tracer> v;
v.reserve(2);
v.emplace_back("a");
v.emplace_back("b");
std::println("full, adding c");
v.emplace_back("c");
}Output
full, adding c copy a copy b
With the Tracer from earlier, whose move constructor is noexcept, the same main moves:
#include <print>
#include <string>
#include <utility>
#include <vector>
int main() {
std::vector<Tracer> v;
v.reserve(2);
v.emplace_back("a");
v.emplace_back("b");
std::println("full, adding c");
v.emplace_back("c");
}Output
full, adding c move a move b
The reason is a promise std::vector makes: if growing fails with an exception (Exceptions covers them), the vector is left as it was. While it copies, the old elements stay untouched, so on a failure it throws the new block away. If a move threw halfway, some old elements would already be emptied, and there’d be no way back. So unless the move constructor promises not to throw, the vector copies. Only a type that can’t be copied at all is moved anyway, and then the vector loses that promise.
PerformanceMark your moves noexcept
A move constructor that only takes pointers and sizes can’t fail, so say so with noexcept. Without it, every time a vector of your type grows, it deep-copies every element. Moves the compiler writes are noexcept by themselves when every member’s move is, which is one more reason for the rule of zero.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
| Rule of zero | Almost always: the members are values, containers, strings or smart pointers. | The compiler’s copies and moves are correct and noexcept where they can be, and there’s nothing to get wrong. | Declare none of the five. |
| Move-only | Copying would be wrong (a unique resource) or too costly to allow by accident. | Copies don’t compile; moves hand the object over. | Copies = delete, moves = default, or a std::unique_ptr member. |
| Rule of five | The class itself owns a raw resource, such as memory from new[] or a handle from a C library. | Each of the five must handle the resource, or two objects end up freeing it. | Write all five; mark the moves noexcept. |
std::move | You hand over a variable you won’t use again. | Its contents are taken instead of copied. | v.push_back(std::move(s));, never on the variable in return. |
Rule of thumb: write none of the five; if you must write one, declare all five.
Under the hood
A std::vector or a long std::string moves the way Buffer does: a few pointers and sizes change hands, whatever the number of elements, while a copy allocates and copies them all. (A short string kept inside the object by the small-string optimization, from string and string_view, has its characters copied by a move, but that’s only a few bytes.)
Often there isn’t even a move. When a function returns a local variable by value, the compiler can build that variable directly in the caller’s object, so nothing is copied or moved. This is copy elision:
#include <print>
#include <string>
#include <utility>
Tracer load(const std::string& name) {
Tracer t(name);
return t; // built directly in the caller's variable
}
int main() {
Tracer reads = load("reads.fastq");
std::println("loaded {}", reads.name);
}Output
loaded reads.fastq
Neither “copy” nor “move” is printed. For a named local like t, copy elision is allowed but not guaranteed; GCC and Clang do it here even without optimization. If a compiler can’t, it moves the returned local, and copies only if the type has no move constructor.
Modern C++Returning a temporary never copies
Since C++17, return Tracer(name);, which returns a temporary rather than a named variable, is guaranteed to build the object in the caller’s variable. The type doesn’t even need a copy or move constructor. So returning big objects by value is the normal way to return them.
std::move itself compiles to nothing. It’s essentially static_cast<T&&>(x) with a readable name: it changes which function is chosen, and the chosen move constructor does the work.
Common pitfalls
return std::move(local)
std::move in a return turns copy elision off: the compiler must now build the result by moving from id, an extra step for nothing. GCC and Clang warn about this with -Wpessimizing-move, which -Wall turns on:
#include <string>
#include <utility>
std::string make_id(int n) {
std::string id = "read_" + std::to_string(n);
return std::move(id);
}
int main() {
std::string id = make_id(7);
}The compiler rejects this
main.cpp: In function ‘std::string make_id(int)’:
main.cpp:6:21: error: moving a local object in a return statement prevents copy elision [-Werror=pessimizing-move]
6 | return std::move(id);
| ~~~~~~~~~^~~~
main.cpp:6:21: note: remove ‘std::move’ call
cc1plus: all warnings being treated as errorsThe fix is return id;. Returning a local already moves it when it can’t be elided.
Using an object after moving from it
With the moving Buffer from earlier, after the move image.data is nullptr, so reading image.data[0] follows a null pointer. That’s undefined behavior, and UndefinedBehaviorSanitizer stops the program:
#include <cstddef>
#include <print>
#include <utility>
int main() {
Buffer image(3);
Buffer moved = std::move(image);
float first = image.data[0]; // image gave its floats away
std::println("{}", first);
}This fails when it runs
main.cpp:9:31: runtime error: load of null pointer of type 'float'
The fix is to read moved.data[0], or to give image a new value before using it again.
std::move on a const object copies
A const object can’t be emptied, so std::move of it gives a const Tracer&&. That doesn’t fit the move constructor’s Tracer&&, but it does fit the copy constructor’s const Tracer&, so you get a copy, with no warning:
#include <print>
#include <string>
#include <utility>
int main() {
const Tracer config("config");
Tracer taken = std::move(config); // const: copies
}Output
copy config
Don’t make a variable const if you plan to move from it.
Try it yourself
Try it yourself
Image has a destructor, a copy constructor and deleted assignments. Every push_back copies pixels, and growing the vector copies the first frame again. Add a move constructor so that no pixels are copied.
#include <algorithm>
#include <cstddef>
#include <print>
#include <utility>
#include <vector>
struct Image {
float* pixels;
std::size_t size;
explicit Image(std::size_t n) : pixels(new float[n]{}), size(n) {}
~Image() { delete[] pixels; }
Image(const Image& other) : Image(other.size) {
std::println("copying {} pixels", size);
std::copy_n(other.pixels, size, pixels);
}
Image& operator=(const Image&) = delete;
Image& operator=(Image&&) = delete;
};
int main() {
std::vector<Image> frames;
frames.push_back(Image(1000));
frames.push_back(Image(2000));
std::println("{} frames", frames.size());
}Expected output
2 frames
Show a hint
Add Image(Image&& other) noexcept, which takes other.pixels and other.size and leaves other with nullptr and 0. std::exchange does both in one step.
Show a solution
#include <algorithm>
#include <cstddef>
#include <print>
#include <utility>
#include <vector>
struct Image {
float* pixels;
std::size_t size;
explicit Image(std::size_t n) : pixels(new float[n]{}), size(n) {}
~Image() { delete[] pixels; }
Image(const Image& other) : Image(other.size) {
std::println("copying {} pixels", size);
std::copy_n(other.pixels, size, pixels);
}
Image(Image&& other) noexcept
: pixels(std::exchange(other.pixels, nullptr)),
size(std::exchange(other.size, 0)) {}
Image& operator=(const Image&) = delete;
Image& operator=(Image&&) = delete;
};
int main() {
std::vector<Image> frames;
frames.push_back(Image(1000));
frames.push_back(Image(2000));
std::println("{} frames", frames.size());
}push_back(Image(1000)) passes a temporary, an rvalue, so it now uses the move constructor and copies no pixels. When the vector grows, it moves the first frame too, because the move constructor is noexcept. Without noexcept, growing would still copy it. With the two assignments deleted and the move constructor added, all five are declared.
Saved in this browser only.