gpt4 book ai didi

c++ - 复制构造函数省略?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:20:19 26 4
gpt4 key购买 nike

不太明白为什么我用VC2010用debug模式构建时没有调用这个拷贝构造函数。

class SomeClass
{
public:
SomeClass(int meaningless){}

SomeClass(const SomeClass& sc)
{
cout << "Copy Constructor invoked!" << endl;
}
};

int main()
{
SomeClass test(SomeClass(9999)); // Copy constructor not invoked.
}

我认为这与 RVO 无关,因为我没有返回任何值。

更有趣的是,当我将复制构造函数设为私有(private)时,即使省略了复制构造函数,编译器也不会编译。

最佳答案

这是编译器做的优化。根据语言规范,允许编译器尽可能忽略对复制构造函数的调用。

仅语义检查需要一个可访问的复制构造函数,即使它实际上 没有被调用。语义检查在优化之前完成。

但是,如果您在 GCC 中使用 -fno-elide-constructors 选项编译它,则不会执行复制省略,而是调用复制构造函数。 GCC doc说,

-fno-elide-constructors

The C++ standard allows an implementation to omit creating a temporary which is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases.

对于 MSVC10,您可以使用 /Od根据 MSDN,它关闭了程序中的所有优化。

注意:维基百科有一篇关于 copy elision 的文章

关于c++ - 复制构造函数省略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10201321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com