I have the following c++ class
class Object
{
public:
Object(parameters);
...
const Object& method1(parameters) const;
Object& method2(parameters) const;
private:
}
the method1 and method2 implementations are:
const Object& Object::method1(parameters) const
{
...
Object* _obj = new Object;
...
return *_obj;
}
Object& Object::method2(parameters) const
{
...
Object* _obj = new Object;
...
return *_obj;
}
I have not defined a copy constructor. I know the functions return a reference to the allocated object and I still have to use "delete" to delete it. I would like to avoid wasting memory and preserve information hiding.
Is this the right way to do this, or am I missing something?
This is bad as nothing will ever delete the objects. They will be leaked.
Return smart pointers, a copy of the object without newing it, or the raw pointer.
It depends on the class, but returning a reference to a dynamically allocated object is probably not a good idea.
If the class has value semantics (supports copy and assignment), you should return an actual object; dynamic allocation of objects with value semantics should be avoided.
If the class is a full fledged entity object, whose lifetime is managed by the application, you should probably return a raw pointer.
If the returned object still needs more processing before it
will be managed by the application, you should probably return
std::auto_ptr, or if you can use C++11, std::unique_ptr; the
caller will then release it once the application logic takes
over, and if anything happens in the meantime, the object will
automatically be destructed and the memory freed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With