I have a class that needs to return a class (of the same type). (The real code is 400+ lines) Something like:
SampleClass has some dynamically allocated members, allocated in the constructor and deallocated in the destructor. However, whenever the function above is called, if I output the values in return_value immediately before the return statement, everything is fine. However, incorrect information is returned from the function.Code:SampleClass SampleClass::Member(const SampleClass &c) const { SampleClass return_value; /* Some code that figures return_value */ return return_value; } some_other_function() { SampleClass c, t = SampleClass(500), q; c = t.Member(q); // c != what it should }
This seemed to work fine, until I compiled under a Linux environment. (Windows seems to let you get away with more.)
The best my mind can figure is that return_value's destructor is called before the value is actually returned. (Since it's allocated on the stack.) The only way to avoid this that I can think of is to use pointers and dynamically allocate everything. Is there a Better Way?