这里有理论疑问。阅读一本书,并给出以下语句:StringBad metoo = knot;
其中:
- StringBad 是一个类
- 结是该类的一个对象
作者对复制构造函数说了以下内容:
implementations have the option of handling this statement in two steps: using the copy constructor to create a temporary object and then using assignment to copy the values to the new object.That is, initialization always invokes a copy constructor, and forms using the = operator may also invoke an assignment operator.
我的实现一步完成:
- 使用复制构造函数创建 metoo 对象,与此相同:
StringBad metoo(knot);
我可以理解其他实现可以像这样分两步完成:
- 使用默认构造函数创建一个 metoo 对象,例如:
StringBad metoo;
- 使用重载赋值运算符将结对象分配给 metoo 对象。
但是作者说初始化总是调用复制构造函数。那是对的吗?如果是这样,编译器在某些实现中将遵循哪些步骤以分两步进行?我无法在我的原因中对其进行测试,因为我说过它一步完成。
最佳答案
作者错了。您所拥有的是带有复制初始化的声明语句,实现这一点的唯一方法是通过 StringBad(StringBad const &)
复制构造函数实例化一个新对象。* 赋值运算符将 从不在这种情况下被调用,甚至不需要存在或可访问。
StringBad metoo = knot;
和 StringBad metoo(knot);
这两个变体之间几乎没有区别。
*) 或非常量版本(如果恰好存在并匹配)。
关于c++ - 在对象初始化中复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12018329/