Suppose you have a function that is supposed to return an object, do you generally return a pointer of the object or the object itself? When should you return a pointer/object?
Asked
Active
Viewed 48 times
1 Answers
0
Generally speaking you will probably want to return object references, since that way you are only transferring a copy of the pointer and not a copy of the entire object - especially if the object is large.
My understanding is that you'll only want to return a copy when you're creating an object on the stack within a function - this is because the object will go out of scope when the function returns and will be deleted. Objects created on the heap can be returned by reference but must be deleted later to avoid memory leaks.

Layne Bernardo
- 676
- 3
- 12
-
I would have to disagree with this. Copy elision and move semantics mean returning an object by value is cheap in general, and [modern C++ recommendations](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Ri-raw) suggest using the type of return to indicate ownership vs borrowing semantics. – Silvio Mayolo Feb 12 '21 at 02:12
-
2@SilvioMayolo You may want to go ahead and write a competing answer for this question then - it sounds like you have a deeper understanding of this issue than I do – Layne Bernardo Feb 12 '21 at 02:18