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.