java的复制构造函数_如何从复制赋值运算符调用复制构造函数?

对于复制赋值运算符,可以使用 copy-and-swap idiom .

例如,在您的情况下,您可以将其添加到 IntList 类定义中(给定您的复制构造函数的代码,我假设您的唯一数据成员是 IntNode* first; ):

// --- swap non-member function ---

friend void swap(IntList& a, IntList& b) /* no-fail */ {

// swap data members one by one

std::swap(a.first, b.first);

}

// --- (copy) assignment operator ---

IntList& operator=(const IntList& other) {

IntList temp(other); // copy construction

swap(*this, temp); // swap

return *this;

// destruction of temp ("old *this")

}

实际上,这可能是更好的风格:

// --- swap non-member function ---

friend void swap(IntList& a, IntList& b) /* no-fail */ {

using std::swap; // enable ADL

// swap data members one by one

swap(a.first, b.first);

}

// --- (copy) assignment operator ---

IntList& operator=(IntList other) { // note: take by value

swap(*this, other);

return *this;

}

/* no-fail */ 注释可以在C 98/03中的 throw() (或者仅仅是 /* throw() */ 注释)中替换,在C 11中为 noexcept .

(注意:不要忘记预先包含std::swap的正确 Headers ,即C 98/03中的 ,C 11中的 (您也可以包括两者) . )

备注:这里 swap 函数在类体中定义,但它仍然是非成员函数,因为它是 friend .

查看整个故事的链接帖子 .

(当然,除了复制构造函数之外,还必须提供正确的析构函数定义(请参阅What is The Rule of Three?) . )

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值