Nar*_*rek 5 c++ stdvector copy-assignment c++11
在这里,您可以看到自我分配检查的复制赋值运算符实现:
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;
}
Run Code Online (Sandbox Code Playgroud)
这对于自我分配很有用,但对性能有害:
所以,我还是不明白,如果我想实现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;
}
Run Code Online (Sandbox Code Playgroud)
另请注意,按值接受参数更为有益.