显式复制构造函数或隐式参数按值 [英] explicit copy constructor or implicit parameter by value
问题描述
我最近读到(不幸的是忘记了在哪里),写operator =的最佳方法是这样的:
I recently read (and unfortunately forgot where), that the best way to write operator= is like this:
foo &operator=(foo other)
{
swap(*this, other);
return *this;
}
代替此:
foo &operator=(const foo &other)
{
foo copy(other);
swap(*this, copy);
return *this;
}
这个想法是,如果使用右值调用operator =,则第一个版本可以优化副本的构造.因此,使用右值调用时,第一个版本会更快,而使用左值调用时,这两个版本是等效的.
The idea is that if operator= is called with an rvalue, the first version can optimize away construction of a copy. So when called with a rvalue, the first version is faster and when called with an lvalue the two are equivalent.
我很好奇其他人对此有何看法?人们会因为缺乏明确性而避免使用第一个版本吗?我是否正确,第一个版本可以做得更好,并且永远不能做得更糟?
I'm curious as to what other people think about this? Would people avoid the first version because of lack of explicitness? Am I correct that the first version can be better and can never be worse?
推荐答案
You probably read it from: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
我没有太多要说的,因为我认为该链接很好地解释了基本原理.有趣的是,我可以确认第一种形式使用MSVC生成的副本数量较少,这是有道理的,因为编译器可能无法在第二种形式上执行复制删除操作.我同意第一种形式是一种严格的改进,并且永远不会比第二种形式差.
I don't have much to say since I think the link explains the rationale pretty well. Anecdotally I can confirm that the first form results in fewer copies in my builds with MSVC, which makes sense since compilers might not be able to do copy-elision on the second form. I agree that the first form is a strict improvement and is never worse than the second.
第一种形式可能不太惯用,但我认为它不太清楚. (IMO,这比第一次看到赋值运算符的复制和交换实现更令人惊讶.)
The first form might be a bit less idiomatic, but I don't think it's much less clear. (IMO, it's not any more surprising than seeing the copy-and-swap implementation of the assignment operator for the first time.)
编辑#2:糟糕,我的意思是写复制删除,而不是RVO.
Edit #2: Oops, I meant to write copy-elision, not RVO.
这篇关于显式复制构造函数或隐式参数按值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!