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
- AFAIK, GCC produces the correct result here. Why MSVC is giving different results and why it is doing copy construction?
const foo& f = get()
andconst foo f = get()
produces same output because of return value optimization. In this case, which way of writing should be preferred?
Any thoughts..