在类的赋值运算符中,通常需要检查所分配的对象是否是调用对象,这样就不会搞砸了:
Class& Class::operator=(const Class& rhs) {
if (this != &rhs) {
// do the assignment
}
return *this;
}
Run Code Online (Sandbox Code Playgroud)
移动赋值运算符需要相同的东西吗?是否有过这样的情况this == &rhs?
? Class::operator=(Class&& rhs) {
?
}
Run Code Online (Sandbox Code Playgroud) 参考http://en.wikipedia.org/wiki/Copy_elision
我运行下面的代码:
#include <iostream>
struct C {
C() {}
C(const C&) { std::cout << "Hello World!\n"; }
};
void f() {
C c;
throw c; // copying the named object c into the exception object.
} // It is unclear whether this copy may be elided.
int main() {
try {
f();
}
catch(C c) { // copying the exception object into the temporary in the exception declaration.
} // It is also unclear whether this copy may be …Run Code Online (Sandbox Code Playgroud)