Re: When are data structures copied
On 7 Nov., 03:04, ShaunJ <sjack...@gmail.com> wrote:
On Nov 6, 2:27 pm, Seungbeom Kim <musip...@bawi.org> wrote:
string s(100, 'x');
map<string, vector<int>> m;
make_pair creates a new pair object and returns it by value, so "in
principle" s and v will be copied. Of course, the compiler is allowed to
perform any optimizations that doesn't change the observable behavior,
so there's no "guarantee" that the copies will be made.
Since s and v are lvalues they will be copied. Now, if that means that
all the characters of that string object are duplicated is another
questions and depends on whether the implementation uses CoW or not.
Recent libstdc++ Versions still use CoW (in a thread-safe way) for
std::string. I'm not sure about std::vector. Probably not.
In C++0x you will be able to use make_pair(T1&&, T2&&) and "move" s and
v, avoiding the copies. As far as I know, the syntax will probably be
m.insert(make_pair(move(s), move(v))) (with all std:: omitted).
"In principle" then, would m.insert(pair<string, vector<int>>(s, v));
avoid making a copy?
No. They have to be copied since s and v are lvalues. Bug again, that
doesn't imply that the string's elements are copied (due to CoW). But
CoW is not mandated, only a possibility.
In C++0x you will be able to write
without having to worry about any copying. The pair object will be
directly constructed "into the map" using its templated constructor
that forwards the rvalues references of move(s) and move(v) to the
constructors of std::string and std::vector.
I had been treating make_pair as a syntatic nicety, but completely
equivalent to the constructor of pair.
I think it's safe to say that is is if your compiler supports RVO
(return value optimization) and inlining. You can expect make_pair to
be as efficient as a direct constructor call. If you're concerned
about the performance you could do something like this:
This will create a pair with a copied string as key and a default-
constructed vector. The new vector is immediately swapped with v.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]