按地址复制构造函数
我有两个复制构造函数
Foo(Foo &obj){
}
Foo(Foo *obj){
}
什么时候会调用第二个复制构造函数?
I have two copy constructors
Foo(Foo &obj){
}
Foo(Foo *obj){
}
When will the second copy constructor will get called?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,你没有 - 你有一个复制构造函数
不是复制构造函数,并且永远不会被 C++ 编译器这样使用。您当然可以自己使用它:
另请注意,您真正的复制构造函数应声明为;
尽管缺少 const 并不妨碍它成为复制构造函数。
No you don't - you have one copy constructor
is not a copy constructor, and will never be used as such by the C++ compiler. You can of course use it yourself:
Note also that your real copy constructor should be declared as;
though the lack of const does not prevent it from being a copy constructor.
暂且不说第二个构造函数不是复制构造函数 - 您实际上想知道何时调用第二个构造函数。
Foo(Foo* obj);
构造函数是单参数构造函数 - 因为它没有用explicit
关键字标记,所以它提供了从Foo*
到Foo
的隐式转换。当使用Foo*
代替Foo
或const Foo&
时,它可能会在任何时候被调用 - 如果它被意外调用,这几乎肯定是正在发生的事情。一般来说,单参数构造函数应该是复制构造函数(其他答案已经解释过)或者应该标记为显式。应谨慎使用提供隐式转换的构造函数。
Leaving aside that the second constructor isn't a copy constructor - you actually wanted to know when the second constructor will be called.
The
Foo(Foo* obj);
constructor is a single parameter constructor - because it hasn't been marked with theexplicit
keyword, it provides an implicit conversion fromFoo*
toFoo
. It may be called at any time where aFoo*
is used in the place of aFoo
orconst Foo&
- if it's being called unexpectedly, that's almost certainly what's happening.In general, single parameter constructors should either be copy constructors (which other answers have explained) or should be marked
explicit
. Constructors which provide implicit conversions should be used sparingly.第二个不是复制构造函数。它是一个构造函数,当您创建一个新的 Foo 对象时会调用它,并给出一个指向 Foo 的指针作为参数。
The second is not a copy constructor. It is a constructor that gets called when you create a new Foo object, giving a pointer to a Foo as parameter.
您的构造函数之一是复制构造函数,另一个只是普通的构造函数。
如果您从指向
Foo
的指针显式初始化Foo
,或者在从指向Foo
的指针转换为调用右值Foo
,例如参数传递和函数返回。进行这样的隐式转换通常是一个坏主意;它可能会在您没有预料到的时候发生,并且很容易将编译错误中的微不足道的拼写错误转变为运行时的异常行为。
One of your constructors is a copy constructor, the other is just a normal constructor.
The second will be called if you explicitly initialize a
Foo
from a pointer toFoo
or in other situations where an conversion from a pointer toFoo
to an r-valueFoo
is called for, such as argument passing and function returns.It's usually a bad idea to have such an implicit conversion; it may occur when you don't expect it to and is liable to turn trivial typos from compile errors into unusual behaviour at runtime.