为什么在这种情况下不调用赋值运算符以支持复制构造函数? [英] Why is the assignment operator not called in this case in favor of the copy constructor?

查看:122
本文介绍了为什么在这种情况下不调用赋值运算符以支持复制构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从复制构造函数的维基百科页面:

  X a = X 

//因为第二个需要非常数X& copy_from_me,所以给定X(X& copy_from_me)
//创建一个,编译器首先通过调用X的默认构造函数
//创建一个临时,然后使用拷贝构造函数初始化为该临时的副本。
//对于一些编译器,这两个版本实际上是工作,但是这个行为不应该依赖
//因为它是非标准的。


编译器首先通过调用X的默认
构造函数创建一个临时函数,然后使用拷贝构造函数初始化为该临时函数的
副本。


我的问题是(假设这是正确的)为什么是这样的?从代码中,我猜想编译器将在构造一个X后使用赋值运算符。



我猜它的是因为赋值发生在与初始化相同的表达式中?



此外,使用这个公式的原因是什么,而不是一个正常的初始化 X a; 或如果您要复制 X a(b);

解决方案

因为代码构造一个对象。这里的=符号是初始化,而不是赋值。您只能分配给现有对象,而不能分配给正在构建的对象。


From the wikipedia page for copy constructors:

X a = X();     

// valid given X(const X& copy_from_me) but not valid given X(X& copy_from_me)
// because the second wants a non-const X&
// to create a, the compiler first creates a temporary by invoking the default constructor
// of X, then uses the copy constructor to initialize as a copy of that temporary. 
// For some compilers both versions actually work but this behaviour should not be relied 
// upon because it's non-standard.

Specifically the part:

" the compiler first creates a temporary by invoking the default constructor of X, then uses the copy constructor to initialize as a copy of that temporary. "

My question is (assuming this is correct) why is this so? From the code, I would guess that the compiler would use the assignment operator after constructing an X.

I'm guessing its because assignment takes place in the same expression as initialization?

Also, what would be the reason to use this formula, rather than just a normal initialization X a; or if you want to copy X a(b); ?

解决方案

Because the code is constructing an object. The = sign here is initializing, not assigning. You can only assign to an existing object, not to one that's under construction.

这篇关于为什么在这种情况下不调用赋值运算符以支持复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆