Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why copy constructor is not called in this case?

Here is the little code snippet:

class A
{
public:
    A(int value) : value_(value)
    {
        cout <<"Regular constructor" <<endl;
    }

    A(const A& other)   : value_(other.value_)  
    {
        cout <<"Copy constructor" <<endl;
    }

private:
    int value_;
};
int main()
{
    A a = A(5);
}

I assumed that output would be "Regular Constructor" (for RHS) followed by "Copy constructor" for LHS. So I avoided this style and always declared variable of class as A a(5);. But to my surprise in the code above copy constructor is never called (Visual C++ 2008)

Does anybody know if this behavior is a result of compiler optimization, or some documented (and portable) feature of C++? Thanks.

like image 850
BostonLogan Avatar asked Nov 18 '09 18:11

BostonLogan


1 Answers

From another comment: "So by default I should not rely on it (as it may depend on the compiler)"

No, it does not depend on the compiler, practically anyway. Any compiler worth a grain of sand won't waste time constructing an A, then copying it over.

In the standard it explicitly says that it is completely acceptable for T = x; to be equivalent to saying T(x);. (§12.8.15, pg. 211) Doing this with T(T(x)) is obviously redundant, so it removes the inner T.

To get the desired behavior, you'd force the compiler to default construct the first A:

A a;
// A is now a fully constructed object,
// so it can't call constructors again:
a = A(5);
like image 104
GManNickG Avatar answered Sep 28 '22 08:09

GManNickG