Possible Duplicate:
how to “return an object” in C++
Hello, guys!
If I need to return an object from function (and it is not a getter, and also this function for some reason cannot be implemented as a constructor, for example there is a constructor with the same signature and different semantics), how better to implement this?
For example, one can propose the following options:
1) Return an object itself:
MyClass GetMyClass() {
MyClass a;
...
return a;
}
In most cases RVO, http://en.wikipedia.org/wiki/Return_value_optimization is performed, no copy constructors is called and there is no overhead. The drawback of this approach is that despite RVO, you must specify the copy construtor of MyClass, but as mentioned in Google C++ Style Guide...
Implicit copying of objects in C++ is a rich source of bugs and of performance problems.
2) Return a pointer to an object:
MyClass* GetMyClass() {
MyClass* a= new MyClass();
...
return a;
}
In such case, there is an overhead because of allocating memory on heap. This somehow slows down the program due to malloc system call. Also, you should free memory outside of this function, which means that allocating and releasing performed in different logical units. As mentioned here, Why malloc memory in a function and free it outside is a bad idea? it is more often a bad idea.
3) Pass value by reference or by pointer:
void GetMyClass(MyClass& a) {
...
}
In this case, code becomes ugly and poorly readable
What is the best practice? Which one do you use in your projects and which criteria are the most important when you are working on a big project?
Two is pretty straightforward. Yes, malloc can be slow, but does it matter in your case? You need space for that object from somewhere. Also note the answers in the question you point to, it's only across logical units that there is an issue. See if you have the problem and then try to fix it rather than pre-optimizing.
You could potentially make your own version of new that uses a free store and managers resources itself. However, unless you've measured and found new to be a problem it's error prone.
One way you can help ameliorate problems with freeing pointers is by using a std::shared_ptr. That way you don't have to worry about freeing the object as long as you always use it through the smart pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With