Copying a large object copies all its data — expensive. Move semantics transfer ownership instead:
vector<int> makeData() {
vector<int> v(1000000, 42);
return v; // moved out, not copied (NRVO / move)
}
auto data = makeData(); // no million-element copy!
string s1 = "Hello, World!";
string s2 = move(s1); // s2 gets the data; s1 is now empty
cout << s2; // Hello, World!
cout << s1.empty(); // true
class Buffer {
int* data; int size;
public:
Buffer(Buffer&& other) // && means rvalue reference
: data(other.data), size(other.size) {
other.data = nullptr; // leave other in valid state
other.size = 0;
}
};
Write buildString(vector<string> words, string sep) that joins words with sep between them.
Click "Run" to execute your code.