Please consider the following code,
struct foo
{
foo()
{
std::cout << "Constructing!" << std::endl;
}
foo(const foo& f)
{
std::cout << "Copy constructing!" << std::endl;
}
~foo()
{
std::cout << "Destructing.." << std::endl;
}
};
foo get()
{
foo f;
return f;
}
int main()
{
const foo& f = get();
std::cout << "before return" << std::endl;
return 0;
}
Output on MSVC
Constructing!
Copy constructing!
Destructing..
before return
Destructing..
Output of GCC
Constructing!
before return
Destructing..
The result which comes on MSVC looks incorrect.
Questions
const foo& f = get()
and const foo f = get()
produces same output because of return value optimization. In this case, which way of writing should be preferred?Any thoughts..
Your MSVC build has no optimizations on. Turn them on, you'll get identical output for both.
GCC is merely performing, by default, RVO on your temporary. It's basically doing:
const foo& f = foo();
MSVC is not. It's making the foo
in the function, copying it to the outside the function (ergo the copy-constructor call), destructing the inner foo
, then binds the reference.
Both outputs are correct. RVO is one instance where the standard explicitly allows the observable behavior of the program to change.