"solid" <[EMAIL PROTECTED]> writes: > Hi, I'm using g++ version 3.4.2 and the following program behaves > strangly: > class A { > public: > A(bool b) : b_(b) {} > A(const A& a) { b_ = !a.b_; } > bool get() const { return b_; } > private: > bool b_; > }; > > #include <iostream> > using namespace std; > int main() { > A x = A(A(true)); > cout << x.get() << endl; > } > > It outputs 1 rather than 0, specifically the copy constructor is not > called. Changing > A x = A(A(true)); > to > A y = A(true); > A z = A(y); > cout << z.get() << endl; > outputs 0. > WHY???
Because the compiler is allowed to optimize away copy-ctor calls (in certain circumstances). So having side effect in copy ctors will yield unpredictable results. Your example program may produce different results depending on the type of compiler and the optimization level you use. -- dt However, experience shows that for many people and many applications a dose of paranoia is reasonable - Bjarne Stroustrup _______________________________________________ help-gplusplus mailing list help-gplusplus@gnu.org http://lists.gnu.org/mailman/listinfo/help-gplusplus