按照operator =实现复制构造函数 [英] Implementing the copy constructor in terms of operator=
问题描述
如果 operator =
已正确定义,可以使用以下作为复制构造函数吗?
If the operator=
is properly defined, is it OK to use the following as copy constructor?
MyClass::MyClass(MyClass const &_copy)
{
*this = _copy;
}
推荐答案
c $ c> MyClass 有一个默认的构造函数,是的。
If all members of MyClass
have a default constructor, yes.
注意,通常情况下是这样:
Note that usually it is the other way around:
class MyClass
{
public:
MyClass(MyClass const&); // Implemented
void swap(MyClass&) throw(); // Implemented
MyClass& operator=(MyClass rhs) { rhs.swap(*this); return *this; }
};
我们传递 operator =
中的值复制构造函数被调用。注意,一切都是异常安全的,因为 swap
保证不抛出(你必须确保在你的实现中)。
We pass by value in operator=
so that the copy constructor gets called. Note that everything is exception safe, since swap
is guaranteed not to throw (you have to ensure this in your implementation).
根据请求编辑有关按值调用的内容: operator =
可写为
EDIT, as requested, about the call-by-value stuff: The operator=
could be written as
MyClass& MyClass::operator=(MyClass const& rhs)
{
MyClass tmp(rhs);
tmp.swap(*this);
return *this;
}
C ++学生通常被要求通过引用传递类实例,因为复制构造函数如果它们通过值传递的话。在我们的例子中,我们必须复制 rhs
,所以传递的值很好。
C++ students are usually told to pass class instances by reference because the copy constructor gets called if they are passed by value. In our case, we have to copy rhs
anyway, so passing by value is fine.
code> operator = (第一个版本,按值调用)为:
Thus, the operator=
(first version, call by value) reads:
-
rhs
(通过复制构造函数自动调用) - 使用
* this
- 返回
* this
,并让rhs
- Make a copy of
rhs
(via the copy constructor, automatically called) - Swap its contents with
*this
- Return
*this
and letrhs
(which contains the old value) be destroyed at method exit.
现在,我们为这个值调用额外的额外奖励。如果传递给 operator =
(或任何通过值获得其参数的函数)的对象是一个临时对象,编译器可以没有)没有复制。这称为复制elision 。
Now, we have an extra bonus with this call-by-value. If the object being passed to operator=
(or any function which gets its arguments by value) is a temporary object, the compiler can (and usually does) make no copy at all. This is called copy elision.
因此,如果 rhs
制成。我们还有:
Therefore, if rhs
is temporary, no copy is made. We are left with:
- 交换
这
和 - 销毁
rhs
- Swap
this
andrhs
contents - Destroy
rhs
在这种情况下,传递值比通过引用传递的效率更高。
So passing by value is in this case more efficient than passing by reference.
这篇关于按照operator =实现复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!