简体   繁体   English

非原始成员初始化中的复制构造函数

[英]copy constructor in a member initialization for non-primitive

I can get no definitive academic answer and testing has proven to be indecisive; 我无法获得确切的学术答案,并且测试已被证明是举棋不定的; and most examples of member initializations use primitives, such as 成员初始化的大多数示例都使用原语,例如

Rectangle::Rectangle (int x, int y) : width(x), height(y) { }

Im seeking member initializations with references, 我正在寻找带有引用的成员初始化,

Shape::Shape (Rectangle& r) : rect(r) {}

Is the latter initialization of rect(r) using the default copy constructor (of Rectangle) or is it a short form of rect = r ?? 后者是使用默认的副本构造函数(Rectangle的)初始化rect(r)还是rect = r的缩写?

Testing has shown me that constructors can be (are) used but i cannot observe the similar behavior for copy constructors 测试表明,可以使用构造函数,但是我无法观察到复制构造函数的类似行为

Shape::Shape (string& str) : rect(str) {}

For this purpose, Rectangle has a Rectangle:Rectangle(string&) constructor 为此,Rectangle具有一个Rectangle:Rectangle(string&)构造函数

Constructors are always used in that syntax. 构造函数始终以该语法使用。 It can't be assignment, because you can only assign to constructed objects, so it'd be running a constructor and then assigning... rest assured, the language won't do something like that. 它不能被赋值,因为您只能赋给已构造的对象,因此它将运行一个构造函数, 然后赋值……放心,该语言将不会做类似的事情。

To help illustrate the difference between constructors and assignment... Rectangle rect = r; 为了帮助说明构造函数和赋值函数之间的区别,... Rectangle rect = r; invokes the constructor, not assignment, despite it's appearance. 调用构造函数,而不是赋值,尽管它看起来很漂亮。 But once rect is already declared, rect = r; 但是,一旦rect已经宣布, rect = r; is assignment. 是分配。 Assignment only makes sense when rect already exists, which can't happen during the initial construction of that object because it doesn't exist yet. 分配仅在rect已经存在时才有意义,因为该对象尚不存在,所以在该对象的初始构造期间不会发生分配。

Also, in your testing, you might be getting confused by Copy Elision. 另外,在测试中, Copy Elision可能会使您感到困惑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM