Please note the following:
class CMyClass { public: CMyClass() { printf( "Constructor\n" ); } CMyClass( const CMyClass& ) { printf( "Copy constructor\n" ); } }; int main() { std::list<CMyClass> listMyClass; listMyClass.resize( 1 ); return 0; }
It produces the following output:
Constructor
Copy constructor
Now my question is: how to avoid copy constructor? Or in another way: how can I create objects inside an STL container without an unnecessary copy operation. Is there a way to make the construction in place using the default constructor?
Update - answers so far:
- It is impossible to do
- Use pointers or smart pointers instead.
Smart pointers are redundant for my application. But I really wonder why this cannot be done. This seems like such an obvious thing to do. Any other ideas? I will even accept a nasty hack if it works ...
Decision
I think I found a solution to my problem from all the comments and answers given here. The solution is to create an empty object and save it for the sole purpose of using it later to create clean copies. Then you can use one of the methods that accept the link (for example, push_back or insert). This still calls the copy constructor for each inserted new object, but at least it is not the constructor of the AND constructor and the default constructor:
int main() { CMyClass Empty; std::list<CMyClass> listMyClass; for ( int c=0; c<10; ++c ) { listMyClass.push_back( Empty ); } return 0; }
c ++ stl
Barnett
source share