When the capacity of an ::std::vector<T>
is reached and an additional element is inserted, it appears that ::std::vector<T>
copy-constructs the data after reallocating a larger portion of memory.
This seems horribly inefficient if for instance we have a vector<vector<vector<int>>>
because the entire content must be deep-copied. If move semantics were exploited the overhead would (typically) be constant per entry, as opposed to unbounded.
Question(s)
- Why does it do this?
- Can I force it to
::std::move
the contents?
Example
To analyse this, I implemented a small wrapper type DataPrinter
that holds a char
and basically cout
s each construction/destruction. And I get this:
::std::vector<DataPrinter> v;
::std::cout << "emplacing a\n";
v.emplace_back('a');
::std::cout << "emplacing b\n";
v.emplace_back('b');
::std::cout << "emplacing c\n";
v.emplace_back('c');
emplacing a
[0x60200000eff0] DataPrinter(a)
emplacing b
[0x60200000efd1] DataPrinter(b)
[0x60200000efd0] DataPrinter(DataPrinter[a]const &)
[0x60200000eff0] ~DataPrinter[a]()
emplacing c
[0x60200000efb2] DataPrinter(c)
[0x60200000efb0] DataPrinter(DataPrinter[a]const &)
[0x60200000efb1] DataPrinter(DataPrinter[b]const &)
[0x60200000efd0] ~DataPrinter[a]()
[0x60200000efd1] ~DataPrinter[b]()
I am building with clang++ 3.5.0-10
and -fsanitize=address -std=c++1z
.