How to initialise a STL vector/list with a class without invoking the copy constructor

Posted by Warpspace on Stack Overflow See other posts from Stack Overflow or by Warpspace
Published on 2010-04-05T18:26:03Z Indexed on 2010/04/05 18:33 UTC
Read the original article Hit count: 246

Filed under:
|
|
|

I have a C++ program that uses a std::list containing instances of a class. If I call e.g. myList.push_back(MyClass(variable)); it goes through the process of creating a temporary variable, and then immediately copies it to the vector, and afterwards deletes the temporary variable. This is not nearly as efficient as I want, and sucks when you need a deep copy.

I would love to have the constructor of my class new something and not have to implement a copy constructor just to allocate my memory for the second time and waste runtime. I'd also rather not have to immediately find the class instance from the vector/list and then manually allocate the memory (or do something horrible like allocate the memory in the copy constructor itself).

Is there any way around this (I'm not using Visual Studio BTW)?

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl