Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning C++ Object - Best Practice [duplicate]

Tags:

c++

oop

I am new to C++ and I'm stuck at the following problem:

Imagine you have a function that creates a new object and returns this object. What is the best approach to do that? I have found 3 different solutions.

Solution 1 Using the copy constructor

MyClass getMyClass() {
    MyClass obj;
    //work with obj, set values...
    return obj;
}

As far as I understod it, you create a new object, copy that object, destroy the first and return the copied object. So I created two object, but I only needed one. Is that right?

Solution 2 Creat the object on the heap and use pointer

MyClass* getMyClass() {
    MyClass* obj = new MyClass();
    //work with obj, set values...
    return obj;
}

This seems to be the worst solution, you have to do memory management on your own.

Solution 3 Pass the object as a parameter

MyClass getMyClass(MyClass& obj) {
    //work with obj, set values...
    return obj;
}

You create a default object and set all values in the function.

I also thaught about using unique_ptr<MyCLass> but there is the same problem, that the unique_ptr is destroyed when the function scope is left.

like image 422
Ennosigaeon Avatar asked Apr 30 '14 09:04

Ennosigaeon


1 Answers

Solution 1 does not use the copy constructor but return value optimization. It means that the object constructed in the function is actually not copied but passed to the caller of the function directly. Solution 1 is a very good option which I would recommend for non-polymorphic objects (i.e. no inheritance) which do not use too much space on the stack.

The preferred method for polymorphic objects would be Solution 2. But always think about who owns your objects, i.e. who is responsible for calling delete. A good alternative is using shared_ptr or unique_ptr.

Solution 3 does not really create the object, it only works with it once it is already created. It also does not make sense to return the object here.

like image 175
Danvil Avatar answered Sep 21 '22 02:09

Danvil