C++ Programming: Objects, RAII and the STL ยท Memory and Ownership
Copying a string duplicates its text; moving it just hands the text over and leaves the source empty.
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
int main() {
string big = "a long piece of text that lives on the heap";
string copied = big; // copy: both have their own text
string moved = move(big); // move: moved takes the text; big is left empty
vector<string> list;
list.push_back(move(copied)); // moved into the vector, no copy made
cout << big.size() << " " << moved.size() << " " << list[0].size() << endl;
return 0;
}int main().big is created on the stack with the value "a long piece of text that lives on the heap".list is created on the stack with the value [].0 43 43.0.