Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ STL container and in-place construction
    text
    copied!<p>Please consider the following:</p> <pre><code>class CMyClass { public: CMyClass() { printf( "Constructor\n" ); } CMyClass( const CMyClass&amp; ) { printf( "Copy constructor\n" ); } }; int main() { std::list&lt;CMyClass&gt; listMyClass; listMyClass.resize( 1 ); return 0; } </code></pre> <p>It produces the following output:</p> <blockquote> <p>Constructor</p> <p>Copy constructor</p> </blockquote> <p>Now my question is: How do I avoid the copy constructor? Or to put it in another way: How can I create objects inside an STL container without the unnecessary copy operation. Is there some way to do an "in-place" construction using the default constructor?</p> <hr> <p>Update - answers so far:</p> <ol> <li>It can't be done</li> <li>Use pointers or smart pointers instead.</li> </ol> <p>Smart pointers are an overkill for my application. But I really wonder why this can't be done. It seems like such an obvious thing to want to do. Any other ideas? I will even accept a nasty hack if it works...</p> <hr> <p>Solution</p> <p>I think I just found a solution for my problem from all the comments and answers posed here. The solution is to construct an empty object and to keep it around for the sole purpose of using it later for making clean copies of. Then you can use one of the methods that take a reference (like push_back or insert). This still calls the copy constructor for every new object inserted, but at least it is not both the default constructor AND copy constructor:</p> <pre><code>int main() { CMyClass Empty; std::list&lt;CMyClass&gt; listMyClass; for ( int c=0; c&lt;10; ++c ) { listMyClass.push_back( Empty ); } return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload