Assignment operator - Self-assignment
Does the compiler generated assignment operator guard against self assignment?
class T {
int x;
public:
T(int X = 0): x(X) {}
};
int main()
{
T a(1);
a = a;
}
Do I always开发者_JAVA技巧 need to protect against self-assignment even when the class members aren't of pointer type?
Does the compiler generated assignment operator guard against self assignment?
No, it does not. It merely performs a member-wise copy, where each member is copied by its own assignment operator (which may also be programmer-declared or compiler-generated).
Do I always need to protect against self-assignment even when the class members aren't of pointer type?
No, you do not if all of your class's attributes (and therefore theirs) are POD-types.
When writing your own assignment operators you may wish to check for self-assignment if you want to future-proof your class, even if they don't contain any pointers, et cetera. Also consider the copy-and-swap idiom.
This is an easy one to check empirically:
#include <iostream>
struct A {
void operator=(const A& rhs) {
if(this==&rhs) std::cout << "Self-assigned\n";
}
};
struct B {
A a;
};
int main()
{
B b;
b = b;
}
class T {
int x;
public:
T(int X = 0): x(X) {}
// prevent copying
private:
T& operator=(const T&);
};
精彩评论