Note that there are some explanatory texts on larger screens.

plurals
  1. POMemory management differences in return by value
    primarykey
    data
    text
    <p>I'm trying to follow a tutorial <a href="http://www.cplusplus.com/doc/tutorial/classes2/" rel="nofollow noreferrer">here:</a> regarding overloading operators, and I've found something that's really confused me.</p> <p>There was a previous question on this very website <a href="https://stackoverflow.com/q/6556413/859249">here</a> where this tutorial was discussed, namely regarding how the variables in the class were preserved because the whole class was passed back by value.</p> <p>Whilst experimenting with the class definition I toyed with making the integer variables pointers (perhaps not sensible - but just to experiment!) as follows:</p> <pre><code>class CVector { int* x; int* y; public: CVector () {}; CVector (int,int); CVector operator + (CVector); ~CVector (); }; </code></pre> <p>In the class constructor I allocate memory for the two integers, and in the class deconstructor I delete the allocated memory.</p> <p>I also tweak the overloaded operator function as follows:</p> <pre><code>CVector CVector::operator+ (CVector param) { CVector temp; *temp.x = *x + *param.x; *temp.y = *y + *param.y; return (temp); } </code></pre> <p>For the original code, where the class has simple integer variables the return by value of the entire class completes successfully. </p> <p>However, after I change the variables to int pointers, the return by value of the class does <strong>not</strong> complete successfully as the integer variables are no longer intact.</p> <p>I assume the deconstructor is being called when the temporary CVector goes out of scope and deletes these member integer pointers, but the class itself is still returned by value.</p> <p>I'd like to be able to return by value the CVector with the memory allocated to its member variables intact, whilst ensuring the temporary CVector is correctly deleted when it goes out of scope.</p> <p>Is there any way this can be done?</p> <p>Many thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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