[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: base constructor
From: |
Dyreatnews |
Subject: |
Re: base constructor |
Date: |
Thu, 09 Mar 2006 10:06:01 +0100 |
User-agent: |
Gnus/5.110003 (No Gnus v0.3) Emacs/22.0.50 (usg-unix-v) |
"solid" <tmuldner@gmail.com> 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