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 need to protect against self-assignment even when the class members aren't of pointer type?
Self assignment check in assignment operator. In C++, assignment operator should be overloaded with self assignment check. For example, consider the following class Array and overloaded assignment operator function without self assignment check. // A sample class. class Array {. private: int *ptr; int size;
For example, consider the following class Array and overloaded assignment operator function without self assignment check. If we have an object say a1 of type Array and if we have a line like a1 = a1 somewhere, the program results in unpredictable behavior because there is no self assignment check in the above code.
Assignment Operators in C/C++ Last Updated: 11-10-2019. Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise ...
So, Assignment Operators are used to assigning values to variables. Now Let’s see each Assignment Operator one by one. 1) Assign: This operator is used to assign the value of the right side of the expression to the left side operand.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With