Does copy elision kick in in this situation? In other words, do modern compilers with copy elision avoid to call any copy constructor here?
class BigObj{};
BigObj fun()
{
BigObj b;
return b;
}
int main()
{
BigObj *pb = new BigObj(fun());
}
I aim to store an object in a pointer. The object is returned by a function. I want to store it without copying it.
I can't use c++11
IMO it is not entirely clear what you aim to achieve. If dynamic allocation is what you want to use, then your function should simply:
... and save yourself the trouble.
Contrary to the previous revision of the answer, it turned out that the compiler can omit a substantial amount of work as long as it is in a static context that can be thoroughly analyzed:
The output verifies that both instances have the same address, so even in the context of a local, the instance is actually not stored in the stack frame of
foo
.Changing to:
to my surprise also output the same address, with both the return by value copy and the copy constructor omitted.
c
infoo
is constructed directly in the memory chunk, allocated bynew
.In conclusion the C++ compiler is pretty smart at analyzing and doing every possible optimization.
Turning off optimizations in the first and second case respectively: