The compiler is plenty smart; you misunderstand memory in C and C++. A common affliction, especially amongst those who have come from a Java or similar background.
and also sticking the address of the object in a global list |
You're
not sticking the address of the object in a global list.
root_list.push_back(n);
This is putting a
copy of the object in a global list. Not the address of the object. A copy of it. You could return the address of that copy, since you know that copy will persist:
Something like
return &(root_list.back());
You missed:
d) Create the object on the heap so it exists until you
delete it, or by using one of the C++11 breed of smart pointers that handle deletion for you
but since you're putting a copy of the object into a global list, you don't need to do that. You can just use that copy, in the global list.
Also:
a.) return the whole object... rather expensive if the object is large, it would be a lot quicker to return just the address. |
Probably
not expensive, no. The compiler is smart enough to use Return Value Optimisation. Unless you go out of your way to make it difficult, the compiler will recognise the opportunity to avoid a copy and simply return the exact same object that was created, rather than a copy of it; no additional expense.