Re: std::vector and object copying
"Tom Widmer [VC++ MVP]" <tom_usenet@hotmail.com> wrote in message
news:OQtqV90cGHA.3556@TK2MSFTNGP02.phx.gbl...
muralibala68@gmail.com wrote:
Hi,
...
std::vector<MyClass> v1;
v1.push_back(MyClass("abc"));
...
The above code results in 2 calls to the 'copy constructor' when I use
Visual C++ (VStudio 2005).
However, it results in a single call to the 'copy constructor' of
MyClass when I use gcc.
Am I missing some compile time optimization option?
It's not a compiler issue, but a library issue. For push_back, VC makes 1
copy when capacity() > size() and 2 copies otherwise. GCC always makes 1
copy. The situation for insert() is more complex.
Yep. And that's because v1.push_back(v1[0]) has to work right, even when
storage for the vector gets reallocated during the push_back.
In any case, by calling reserve() before push_back, you can get rid of the
extra copy in VC.
Yep. At the cost of constructing a default element and copying it.
Alternatively, this hack should get rid of the extra
copy too:
std::vector<Foo> v;
char const* s = "abc";
v.insert(v.end(), &s, &s + 1);
Yep. Because with random-access iterators insert knows enough to handle
even v.insert(v.begin() + 3, &v[2], &v[5]) properly.
P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com