请看以下代码:
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;
}
MSVC输出
Constructing!
Copy constructing!
Destructing..
before return
Destructing..
GCC的输出结果
Constructing!
before return
Destructing..
在MSVC上显示的结果似乎是不正确的。
问题
- 据我所知,GCC在这里产生了正确的结果。为什么MSVC会产生不同的结果,并且为什么它要进行复制构造?
const foo& f = get()
和const foo f = get()
由于返回值优化,产生相同的输出。在这种情况下,应该优先选择哪种写法?
有什么想法..