Reputation: 43
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?
Upvotes: 3
Views: 144
Reputation: 153919
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.
Upvotes: 4
Reputation: 39688
If you're using C++11, you can use std::unique_ptr<object>
or std::shared_ptr<object>
as return types (depending on the use-case). The object will then be destructed automatically as soon as the last smart pointer vanishes.
These classes are also available in boost (well, std::unique_ptr
maps to boost::scoped_ptr
), in case your compiler does not support C++11. You can also use std::auto_ptr
if you need to, but it has been deprecated with C++11.
Upvotes: 2
Reputation: 2520
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.
Upvotes: 4
Reputation: 722
in this case you should use the return value as pointer object* object::methodn(parameters) const
or implement copy constructor and then return not the reference but the copy of the object, because when you look at the declaration of method1
or method2
you can't even imagine that there is created a memory leak inside. Also if you're using C++11 you can use rvalue reference
to ease up on memory using copy contructorhere's some info on C++11 rvalue references
Upvotes: 1