Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ classes and object reference

Tags:

c++

object

class

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?

like image 428
Salvatore Barone Avatar asked Feb 01 '26 04:02

Salvatore Barone


2 Answers

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.

like image 123
Dominique McDonnell Avatar answered Feb 03 '26 16:02

Dominique McDonnell


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.

like image 26
James Kanze Avatar answered Feb 03 '26 18:02

James Kanze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!