None of the two options you asked about is very good. In this particular case you should use shared_ptr
or unique_ptr
, or auto_ptr
if you use older C++ compilers, and change the function so it returns pointer, not reference. Another good option is returning the object by value, especially if the object is small and cheap to construct.
Modification to return the object by value:
SomeObject f() { return SomeObject(); }
SomeObject s(f());
Simple, clean, safe - no memory leaking here.
Using unique_ptr
:
SomeObject* f() { return new SomeObject(); }
unique_ptr<SomeObject> s(f());
One of the advantages of using a unique_ptr
or shared_ptr
here is that you can change your function f
at some point to return objects of a class derived from SomeObject
and none of your client code will need to be changed - just make sure the base class (SomeObject
) has a virtual constructor.
Why the options you were considering are not very good:
Variant 1:
SomeObject& s = f();
How are you going to destroy the object? You will need address of the object to call it's destructor anyway, so at some point you would need to dereference the object that s
refers to (&s
)
Variant 2. You have a leak here and not a chance to call destructor of the object returned from your function.