Consider the following two classes:
class Base { Base(const Base& other) {...}
This means that Base can be "upcast" with the second Derived constructor. Now consider the following code:
Base getBase() { int id = ... return Base(id); } ... int main() { Base b = getBase();
I am using VS2008 with optimizations enabled (/ Ox / Ob2 / Oi / Ot). I checked the calls to the designers and destructors on the console output:
Case 1 optimizes return value. There are two challenges:
However, there is nothing to win when the main object needs a Derived-object. Upcast requires another pair of constructors / destructors.
In Case 2, return value optimization does not work. Two objects are created and destroyed here:
- Base (int) // Create Temporary
- ~ Base () // Destroy temporary
- Base (const Base &) // via Derived (const Base &)
- ~ Base () // via ~ Derived ()
Now it seems to me that I have three conflicting requirements:
- I would like to avoid the overhead of creating a temporary object (since creating and destroying objects is quite expensive in the Base class)
- Basically I need a Derived object instead of the base object to work with.
Obviously there is no free lunch here. But I could have missed something. So my question is: is there a way to combine these requirements? Or did someone have similar experiences?
Sidenote: I am aware that the "upcast" Derived (const Base & other) can fail at runtime (this was taken care of). Since the code is okay at the syntax level, I would suggest that this is not a reason for the compiler to avoid RVO.
source share