Here您可以看到带有自赋值检查的复制赋值运算符实现:
String & operator=(const String & s)
{
if (this != &s)
{
String(s).swap(*this); //Copy-constructor and non-throwing swap
}
// Old resources are released with the destruction of the temporary above
return *this;
}
这有利于 self 分配,但对性能不利:
- 因为每次它检查 if 语句(考虑到分支预测,我不知道它的最优程度是多少)
- 我们在这里也失去了右值参数的复制省略
所以我还是不明白如果我要实现std::vector
的operator=
我会如何实现它。
最佳答案
是的,这段代码是多余的。确实,它导致了额外的不必要的分支。有了适当的交换和移动语义,下面的代码应该会更高效:
String& String::operator=(String s) { // note passing by value!
std::swap(s, *this); // expected to juggle couple of pointers, will do nothing for self-assingment
return *this;
}
另请注意,按值接受参数更有益。
关于c++ - 是否推荐具有 copy-and-swap 习语和自赋值检查的复制赋值运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37125197/