TITLE: self assignment within constructors (Newsgroups: comp.lang.c++, 13 Sept 96) CARR: Glenn Carr (gcarr@lgc.com) : What do you mean by... "If the assignment operator does not depend on : the current values of 'this'" ? KUEHL: kuehl@uzwil.informatik.uni-konstanz.de (Dietmar Kuehl) If you call the assignment operator from the copy ctor, you cannot depend on any class invariants to be established. However, often the assignment operator depends on some invariants. E.g. the following example depends on 'ptr' pointing to an object which is "owned" by 'this' or to be '0'. Since this is not guaranteed, calling 'foo's copy ctor results in undefined behavior. template class foo { T *ptr; public: foo(T const &t): ptr(new T(t)) {} foo(foo const &f) { *this = f; } foo &operator= (foo const &f) { if (&f != this) *ptr = *f.ptr; // oops, 'ptr' is not yet initialized! return *this; } } The call of 'operator=()' from the copy ctor in the above example is problematic because the assigment depends on the current value 'this'. More specifically, it assumes that 'this->ptr' points to memory allocated to hold an object of type 'T'. This is probably not the case. CARR: : Ahh, so does that mean these routines won't even be called for when the : copy ctor and the assignment operator are needed?!? KUEHL: No, not exactly: It just means that you cannot do certain thing which are normally required. It would be impossible to use a constant object to initialize a new object or to assign it to some other object: class foo { public: foo(foo &); foo operator= (foo &); // ... }; void f(foo const &f) { foo copy(f); // illegal: no 'foo(foo const &)' foo assign; assigne = f; // illegal: no 'operator(foo const &)' } Both the assignment and the copy from a constant object are normally necessary. Thus, you should put in the 'const' or at least implement a version of these operations taking a reference to a constant object.