Note that there are some explanatory texts on larger screens.

plurals
  1. POCopying and destruction when returning a C++ object
    text
    copied!<p>I have a fairly simple piece of test code:</p> <pre><code>#include &lt;stdio.h&gt; class PG { public: PG(){ m_ptr = new int; printf("Created PG %i\n", (int)m_ptr); } ~PG(){ printf("Deleted PG %i\n", (int)m_ptr); delete (m_ptr); } PG&amp; operator =(const PG&amp; src) { printf("Copied PG %i %i\n", (int)m_ptr, (int)src.m_ptr); return(*this); } private: int * m_ptr; }; PG CreatePG() { PG ret; return ret; } int main(int argc, char* argv[]) { PG test; test = CreatePG(); printf("Ending\n"); return 0; } </code></pre> <p>If I compile this with GCC, VS2008 or VS2012 with full optimization and run it I get exactly what I expect:<br> Created PG 7837600 <em>-created test</em><br> Created PG 7689464 <em>-created ret</em><br> Copied PG 7837600 768946 <em>-copied ret to test</em><br> Deleted PG 7689464 <em>-deleted ret</em><br> Ending<br> Deleted PG 7837600 <em>-deleted test</em><br></p> <p>However when I compile on VS2008 or VS2012 with no optimization I get this:<br> Created PG 3888456 <em>-created test</em><br> Created PG 4036144 <em>-created ret</em><br> Deleted PG 4036144 <em>-deleted ret. Hang on, we haven't copied it yet!</em><br> Copied PG 3888456 4036144 <em>-We are now trying to copy deleted data</em><br> Deleted PG 4036144 <em>-This has already been deleted. The application crashes</em><br></p> <p>I can't believe that it is a bug in VS that has never been fixed but I also can't see what I am doing wrong. In my application I have an instance where this behaviour also occurs when compiling a more complicated class optimized for speed. I know it would be more efficient to use:</p> <pre><code> PG test = CreatePG(); </code></pre> <p>but I still get a similar problem though it is obviously using copy elision in this case:<br> Created PG 11228488<br> Deleted PG 11228488<br> Ending<br> Deleted PG 11228488<br> I am still getting the double delete.</p> <p>If anyone can throw some light on this I would be very grateful.</p>
 

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