class myObj
{
myObj() {};
}
myObj MakeObj()
{
return( myObj() );
}
main()
{
myObj o = MakeObj();
}
In the MakeObj function, the obj is returned by value. So in the assignment, the created object is copied. It seems there are two operations – one to create the object and assign its fields in MakeObj and another to copy the object on return.
Are one of these steps optimized out by compilers?
What is the fastest way to create a complex object and assign it?
Semantically speaking, in C++03, there are two copies made in the code i.e when it returns from
MakeObj(), but the first copy is usually get optimized away by the compilers. That optimization is referred to as Return Value Optimization.In C++11, the returned object is actually moved (if available and accessible), not copied, which is optimized away by the compilers.