Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 need to protect against self-assignment even when the class members aren't of pointer type?

like image 205
cpx Avatar asked Apr 09 '11 23:04

cpx


People also ask

What is self assignment check in assignment operator in C++?

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;

What is overloaded assignment operator function without self assignment check?

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.

What is the use of assignment operator in C++?

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 ...

What are the assignment operators in JavaScript?

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.


1 Answers

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.

like image 60
Johnsyweb Avatar answered Sep 18 '22 07:09

Johnsyweb