复制构造函数相关问题(本机 c++)
我知道复制构造函数必须有一个引用作为参数,以避免对其自身的“无限次调用”。我的问题是 - 为什么会发生这种情况,其背后的逻辑是什么?
CExample(const CExample& temp)
{
length = temp.length;
}
Possible Duplicate:
Why should the copy constructor accept its parameter by reference in C++?
i know that a copy constructor must have a reference as a parameter, to avoid an 'infinite number of calls' to itself. my question is - why exactly that happens, what is the logic behind it?
CExample(const CExample& temp)
{
length = temp.length;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设你的参数复制 C'tor 是按值传递的,C'tor 要做的第一件事就是复制参数 [这就是每个函数,包括构造函数对按值参数所做的事情]。为了做到这一点,它必须再次调用 C'tor,从原始变量到局部变量......[一遍又一遍......]这最终将导致无限循环。
assume your argument to the copy C'tor was passed by value, the first thing the C'tor would have done, was copying the argument [that's what every function, including constructors do with by-value arguments]. in order to do so, it would have to invoke the C'tor again, from the original to the local variable... [and over and over again...] which will eventually cause an infinite loop.
C++ 中有时会调用复制构造函数。其中之一是当您有一个像这样的函数时
,在这种情况下,当您调用
CExample::CExample
时,会调用CExample::CExample
来从x
构造obj
>。如果您具有以下签名
(请注意,
obj
现在是通过引用传递的),则复制构造函数CExample::CExample
不会 被调用。如果您的构造函数接受按值复制的对象(与第一个示例中的函数
f
一样),编译器必须按顺序调用复制构造函数first创建一个副本(再次与函数f
一样),但是...哎呀,我们必须调用复制构造函数才能调用复制构造函数。这听起来很糟糕,不是吗?Copy constructors are called on some occasions in C++. One of them is when you have a function like
In this case, when you make a call
CExample::CExample
gets called to constructobj
fromx
.In case you have the following signature
(note that
obj
is now passed by reference), the copy constructorCExample::CExample
does not get called.In the case your constructor accepts the object to be copied by value (as with the function
f
in the first example), compiler will have to call the copy constructor first in order to create a copy (as with the functionf
, again), but... oops, we have to call the copy constructor in order to call the copy constructor. This sounds bad, doesn't it?参见此处
“这是一个参考,因为值参数需要制作一个副本,这将调用复制构造函数,这将复制其参数,这将调用复制构造函数,这......”
或者以不同的方式,构造函数的值参数必须调用构造函数复制参数中的值。这个新的构造函数需要做同样的事情 - 导致无限递归!
See here
"It is a reference because a value parameter would require making a copy, which would invoke the copy constructor, which would make a copy of its parameter, which would invoke the copy constructor, which ... "
Or put a different way a value parameter to the constructor would have to call the constructor to copy the value in the parameter. This new constructor would need to do the same - leading to infinite recursion!