加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 类型t = Type()是否调用复制构造函数?

发布时间:2020-12-16 05:07:11 所属栏目:百科 来源:网络整理
导读:我真的很困惑….类型t = Type()调用复制构造函数还是没有? 我问,因为当我尝试: #include iostreamclass Test{public: Test(Test const ) { std::cout "hello"; } Test() { }};int main(){ Test t = Test(); return 0;} 没有输出,但当我改变它 #include ios
我真的很困惑….类型t = Type()调用复制构造函数还是没有?

我问,因为当我尝试:

#include <iostream>

class Test
{
public:
    Test(Test const &) { std::cout << "hello"; }
    Test() { }
};

int main()
{
    Test t = Test();
    return 0;
}

没有输出,但当我改变它

#include <iostream>

class Test
{
    Test(Test const &) { std::cout << "hello"; }
public:
    Test() { }
};

int main()
{
    Test t = Test();
    return 0;
}

我明白了:

error C2248: 'Test::Test' : cannot access private member declared in class 'Test'

这没有意义(特别是因为这是一个调试版本).

更新:

即便这样编译!

struct Test
{
    Test(Test &&) = delete;
    Test(Test const &) = delete;
    Test() { }
};

int main()
{
    Test t = Test();
    return 0;
}

复制/移动构造函数是必需还是否?

解决方法

来自维基百科:

In C++ computer programming,copy elision refers to a compiler
optimization technique that eliminates unnecessary copying of objects.
The C++ language standard generally allows implementations to perform
any optimization,provided the resulting program’s observable behavior
is the same as if,i.e. pretending,the program was executed exactly
as mandated by the standard.

The standard also describes a few situations where copying can be
eliminated even if this would alter the program’s behavior,the most
common being the return value optimization. Another widely implemented
optimization,described in the C++ standard,is when a temporary
object of class type is copied to an object of the same type.[1] As
a result,copy-initialization is usually equivalent to
direct-initialization in terms of performance,but not in semantics;
copy-initialization still requires an accessible copy
constructor
.[2] The optimization can not be applied to a temporary
object that has been bound to a reference.

您正在进行复制构造,但是标准允许将其转换为直接初始化,并且无论调试是否关闭都可以完成,这就是打印未到达的原因.

但是,因为它“应该”是一个复制结构,你需要访问一个,这就是第二个代码不起作用的原因.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读