Self assignment
-
Hi Does anyone know how to prevent self assignment of object. E.g If I have a class A, A a; a = a; // how to prevent this
Refer, http://www.parashift.com/c++-faq-lite/assignment-operators.html#faq-12.3[^].
Prasad MS MVP - VC++
-
Hi Does anyone know how to prevent self assignment of object. E.g If I have a class A, A a; a = a; // how to prevent this
ragavan wrote:
a = a; // how to prevent this
What do you mean "prevent"? You want a compiler error? If you just don't want the assignment to happen you can create an assignment operator and check if the right hand side value s address == this and do not perform the assignment.
led mike
-
Hi Does anyone know how to prevent self assignment of object. E.g If I have a class A, A a; a = a; // how to prevent this
You probably also want to prevent the copy constructor. I guess your question is regarding manual memory management, classes that handle memory/resources might need a decent copy constructor and an assignment operator (or alternatively a prevention of shallow copy). For details please see boost::noncopyable and the Law of the Big Two. In my class designs I sometimes take the easy way and just use 'noncopy' to prevent the shallow copy (which also means users can't make a copy of the objects, which really is fine for some classes). But sometimes you actually want this feature and then I implement both copy contructor and assignment operator (with a check for accidental self assignment). Hope it helps, M