C++复制构造函数调用
快问。如果我有一个数组并且已经正确重载了赋值运算符,那么当我执行以下操作时:
A = B
当 A 和 B 都是数组类型的对象时,我是调用复制构造函数,还是仅调用重载的赋值运算符(=)?
时,会调用复制构造函数
- “传递值”
- 返回类类型的值
- 我知道当一个对象被括号中给出的相同类型的另一个对象声明和初始化时,当
。上面的3让我很困惑,认为A = B也在调用复制构造函数。
难道只是调用重载的赋值运算符吗?
谢谢!
Quick question. If I have an array and have properly overloaded the assignment operator, then when I do something like this:
A = B
When A and B are both objects of type array, am I calling the copy constructor, or just the overloaded assignment operator(=)?
I know that a copy constructor is called when
- Pass By value
- return a value of class type
- when an object is being declared and initialized by another object of the same type given in parenthesis.
3 above makes me confused and thinking that A = B is also calling the copy constructor.
Is it just calling the overloaded assignment operator?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
除非您的复制构造函数被声明为
显式
,否则以下内容确实会调用复制构造函数:我相信标准保证了这一点(我手头没有参考资料),所以您知道您不会调用默认值ctor 后跟赋值运算符。
Unless your copy constructor is declared
explicit
, the following will indeed call the copy constructor:I believe the standard guarantees this (I don't have my reference handy) so you know you will not be calling the default ctor followed by the assignment operator.
以上都不是:您不能分配数组。
如果您有自己的数组类,并且它具有如下所示的内容:
那么这些是等效的:
就像调用函数一样。
None of the above: you cannot assign arrays.
If you have your own array class, and it has something like this:
Then these are equivalent:
It's just like calling a function.
既然您已经说过该数组是您自己的带有重载赋值运算符的类,那么您已经回答了您自己的问题。
复制构造函数实际上仅在您从另一个对象构造对象时才会被调用:
Obj a;
目标 b(a);
如果你这样做的话,它最终可能会被某种编译器魔术调用:
Obj a;
对象 b = a;
但我从来没有费心去真正查找。
如果你只是执行 a = b 你并没有构造 a,因此你不会调用复制构造函数。
有道理吗?
Since you've said the array is your own class with an overloaded assignment operator then you've already answered your own question.
The copy constructor is literally only called when you are constructing the object from another:
Obj a;
Obj b(a);
It might wind up being called by some sort of compiler magic if you do:
Obj a;
Obj b = a;
But I never bothered to actually look that up.
If you just do a = b you are not constructing a, therefore you'd not call the copy constructor.
Make sense?
如果执行
A=B;
,则调用重载赋值运算符如果上面是类定义,则应调用赋值运算符。
Overloaded Assignment Operator is called if performed
A=B;
If the above is the class definition, then assignment operator should be called.
正如您所说,当
考虑以下代码的输出:
Copy constructor is called -as you said- when
Consider the output of the following code :