这是有效的 Copy Ctor 吗?
我想知道下面的复制构造函数是否有问题?
class A
{
private:
int m;
public:
A(A a){m=a.m}
}
I wonder if there is something wrong with the copy constructor function below?
class A
{
private:
int m;
public:
A(A a){m=a.m}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有两件事:
复制构造函数必须将引用作为参数,否则它们是无限递归的(事实上,该语言不允许您声明这样的构造函数)
它不会执行默认复制构造函数不执行的任何操作,但效果很差 - 您应该尽可能在复制构造函数中使用初始化列表。如果默认的复制构造函数执行了您想要的操作,请不要试图自己编写一个版本 - 您可能只会出错,并且需要维护它。
Two things:
Copy constructors must take references as parameters, otherwise they are infinitely recursive (in fact the language won't allow you to declare such constructors)
It doesn't do anything the default copy ctor doesn't do, but does it badly - you should use initialisation lists in a copy ctor wherever possible. And if the default copy ctor does what you want, don't be tempted to write a version yourself - you will probably only get it wrong, and you will need to maintain it.
有3个问题。
首先,你忘记了“;”在 m=am 的末尾,这样你的代码就无法编译。
其次,在大多数情况下,当您传递具有大小的内容时,首选通过引用传递
大于平台上寄存器的大小。
第三,由于您不打算更改源对象,因此最好将其与 const 一起使用。
所以,最后这就是我们所拥有的:
There 3 problems.
First, you have forgot ";" at the end of the m=a.m so your code would not compile.
Second, passing by reference is preferred in most cases where you pass something with size
greater than size of a register on your platform.
Third, since you are not going to change the source object, it is better to have it with const.
So, finally this is what we have:
问题在于,为按值传递的参数调用了复制构造函数。因此,如果您不希望非终止递归,则必须通过引用(通常是 const 引用)传递复制构造函数的参数。一个小问题是您没有使用初始化列表,这更适合初始化成员。解决这两个问题:
The problem is that the copy constructor is called for parameter passed by value. So you have to pass the parameter of the copy constructor by reference (usually const reference) if you don't want a non terminating recursion. A minor issue is that you aren't using the initialization list, which is preferable to initialize the member. Fixing both issues: