【发布时间】:2010-03-05 04:50:48
【问题描述】:
请考虑以下代码,
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 上的结果看起来不正确。
问题
- AFAIK,GCC 在这里产生正确的结果。为什么 MSVC 会给出不同的结果以及它为什么要进行复制构建?
-
由于返回值优化,
const foo& f = get()和const foo f = get()产生相同的输出。在这种情况下,应该首选哪种写作方式?
任何想法..
【问题讨论】:
-
那是因为 gcc 默认开启了 RVO。要关闭它,请使用 gcc 的 -fno-elide-constructors 选项。
标签: c++ return-value-optimization