July 5, 2009
-
C++: Return Value Optimization
class_1 function_1()
{
return class_1(arg_1, arg_2);
}class_1 function_2()
{
class_1 obj_2(arg_1, arg_2);
return obj_2;
}Do these two C++ functions look same? Yes. But do they mean the same thing, or do the compiler generates same assembly code from them? No. In function_2, a temporary object is created ,thus calling its constructor call. Then the object is copied through its copy-constructor to the return object. And the temporary object is deleted.
However in function_1, with a smart enough compiler, there will be no temporary object, and hence no destruction. The object is built directly outside the function, so there is no copy-construction, too. This is a much efficient approach that saves memory and CPU cycle, which is called the return value optimization.