Skip to main content
GameDev.net gamedev.net
🔒 Locked

return an object pointer from a method

Started by Miso Jan 16, 2006 at 1:24 PM 4 replies 800+ views
Original Post
Miso
Miso
Hi everybody! I have a question concerning the lifetime of an object created inside another object's method. Could you please take a look at this? This should be C plus plus code.

class MyReturnedValue
  int a;
};

class MyClass
{
  MyReturnedValue *computeValue();
};


MyReturnedValue *MyClass::computeValue()
{
  MyReturnedValue *pValue = new MyReturnedValue();
  pValue->a = 5;

  return pValue;
}



void main()
{
  MyClass *pClass = new MyClass();

  MyReturnedValue *pValue = pClass->computeValue();

  delete pClass;

  cout pValue->a;; // (*)
}
My question is if pValue will still point at allocated memory at point (*) in the source code. Thanks in advance. Miso
ToohrVyk
ToohrVyk
Yes. Memory allocated with new must always be explicitly deallocated, using delete. Until then, it's valid.
Miso
Miso
Thanks for the quick reply, guys.
ZQJ
ZQJ
I'm surprised nobody's yet pointed out that you should in fact avoid ever having to manually free resources and instead use RIAA classes like std::auto_ptr.
ToohrVyk
ToohrVyk
auto_ptr has the nasty habit of not being an acceptable return type, although it is true that the 'owner' of the object should indeed use an auto_ptr to reference it when it is practical.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.