复制构造函数和赋值运算符
如果我覆盖 operator=
复制构造函数会自动使用 new 运算符吗?同样,如果我定义一个复制构造函数,operator=
会自动“继承”复制构造函数的行为吗?
If I override operator=
will the copy constructor automatically use the new operator? Similarly, if I define a copy constructor, will operator=
automatically 'inherit' the behavior from the copy constructor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不会。除非您定义复制因子,否则将生成默认值(如果需要)。除非您定义运算符=,否则将生成默认值(如果需要)。它们不互相使用,您可以单独更改它们。
No. Unless you define a copy ctor, a default will be generated (if needed). Unless you define an operator=, a default will be generated (if needed). They do not use each other, and you can change them independently.
不,它们是不同的对象。
如果您担心复制构造函数和赋值运算符之间的代码重复,请考虑以下习惯用法,名为 复制和交换:
这样,
operator=
将使用复制构造函数构建一个新对象,该对象将与交换*this
并在函数退出时释放(其中包含旧的this
)。No. They are different objects.
If your concern is code duplication between copy constructor and assignment operator, consider the following idiom, named copy and swap :
This way, the
operator=
will use the copy constructor to build a new object, which will get exchanged with*this
and released (with the oldthis
inside) at function exit.不
,一定要看看三法则
(或五规则考虑右值时)
No.
And definitely have a look at the rule of three
(or rule of five when taking rvalues into account)
考虑以下 C++ 程序。
注意:我的“Vector”类不是标准库中的类。
我的“Vector”类接口:
我的“Vector”类成员实现:
然后,程序输出:
总结:
Vector v2 = v1;
导致调用复制构造函数。在情况 2 中,对象
v3
已经存在(我们已经完成:Vector v3{10};
)。复制构造函数和复制赋值运算符有两个明显的区别。Vector v2
)this
指针。(此外,所有构造函数都不返回值)。Consider the following C++ program.
Note: My "Vector" class not the one from the standard library.
My "Vector" class interface:
My "Vector" class members implementation:
Then, the program output:
To wrap up:
Vector v2 = v1;
lead to call copy constructor.v3 = v2;
lead to call copy assignment operator.In case 2, Object
v3
already exists (We have done:Vector v3{10};
). There are two obvious differences between copy constructor and copy assignment operator.copy construct
a new object. (as itVector v2
)this
pointer.(Furthermore, all the constructor does not return a value).不,他们不是同一个运营商。
No, they are not the same operator.
不,他们是不同的运营商。
复制构造函数用于创建一个新对象。它将现有对象复制到新构造的对象。复制构造函数用于从旧实例初始化新实例
实例。当将变量按值传递给函数时不一定会调用它
或作为函数的返回值。
赋值运算符是处理一个已经存在的对象。赋值运算符用于更改现有实例以使其具有
与右值相同的值,这意味着该实例必须是
如果它有内部动态内存,则被销毁并重新初始化。
有用的链接:
No, they are different operators.
The copy constructor is for creating a new object. It copies an existing object to a newly constructed object.The copy constructor is used to initialize a new instance from an old
instance. It is not necessarily called when passing variables by value into functions
or as return values out of functions.
The assignment operator is to deal with an already existing object. The assignment operator is used to change an existing instance to have
the same values as the rvalue, which means that the instance has to be
destroyed and re-initialized if it has internal dynamic memory.
Useful link :