在复制构造函数中调用赋值运算符 [英] Calling assignment operator in copy constructor

查看:218
本文介绍了在复制构造函数中调用赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这种复制构造函数的实现有一些缺点吗?

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...

推荐答案

是的,理念。用户定义类型的所有成员变量将首先被初始化,然后立即被覆盖。

Yes, that's a bad idea. All member variables of user-defined types will be initialized first, and then immediately overwritten.

这种交换技巧是:

Foo& operator=(Foo rhs) // note the copying
{
   rhs.swap(*this); //swap our internals with the copy of rhs
   return *this;
} // rhs, now containing our old internals, will be deleted 

这篇关于在复制构造函数中调用赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆