在复制构造函数中调用赋值运算符有缺点吗?
这种复制构造函数的实现有一些缺点吗?
Foo::Foo(const Foo& i_foo)
{
*this = i_foo;
}
我记得,在一些书中建议从赋值运算符调用复制构造函数并使用众所周知的交换技巧,但我不记得为什么......
Are there some drawbacks of such implementation of copy-constructor?
Foo::Foo(const Foo& i_foo)
{
*this = i_foo;
}
As I remember, it was recommend in some book to call copy constructor from assignment operator and use well-known swap trick, but I don't remember, why...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是一个坏主意。所有用户定义类型的成员变量都会首先被初始化,然后立即被覆盖。
交换技巧是这样的:
Yes, that's a bad idea. All member variables of user-defined types will be initialized first, and then immediately overwritten.
That swap trick is this:
在构造函数中调用
operator=()
既有潜在的缺点,也有潜在的好处。缺点:
无论您是否指定值,您的构造函数都会初始化所有成员变量,然后
operator=
将再次初始化它们。这增加了执行复杂性。您需要做出明智的决定,以确定何时这会在您的代码中产生不可接受的行为。你的构造函数和
operator=
变得紧密耦合。实例化对象时需要执行的所有操作也将在复制对象时完成。同样,您必须明智地确定这是否是一个问题。收益:
There are both potential drawbacks and potential gains from calling
operator=()
in your constructor.Drawbacks:
Your constructor will initialize all the member variables whether you specify values or not, and then
operator=
will initialize them again. This increases execution complexity. You will need to make smart decisions about when this will create unacceptable behavior in your code.Your constructor and
operator=
become tightly coupled. Everything you need to do when instantiating your object will also be done when copying your object. Again, you have to be smart about determining if this is a problem.Gains:
您正在寻找 Scott Meyers 的《Effective C++》,第 12 项:“复制对象的所有部分”,其摘要指出:
You're looking for Scott Meyers' Effective C++, Item 12: "Copy all parts of an object", whose summary states: