Why destructor is not getting called for anonymous objects?

331 views Asked by At

While working, I came across one strange/confusing piece of code which I feel is related to anonymous object life cycle concept. Below is the sample piece of code:

#include<iostream>
#include<string>

class A {
private:
    int i;
    std::string s;
public:
    A(int ii, std::string ss = "Hello") { i = ii; s = ss; }
    void Display() { std::cout<<i<<"\n"; }
    ~A() { std::cout<<"A::~A()"<<"\n";}
};

void function()
{
    A a = 1;
    //A a = A(1);
    a.Display();
}

int main()
{
    function();
    return 0;
}

Output1(If A a = 1) in VS2010

 1
  A::~A()

Output2(If A a = A(1)) in VS2010

A::~A()
1
A::~A()

The output2 perfectly make sense as destructor gets called twice(including for anonymous) object.

However output1 confuses me and not able to understand why destructor is getting called once(not for anonymous) object.

A a = 1;

Above line would calls the copy-constructor(A(const A& rhs)) of class A and for which compiler should create the anonymous object using parameter 1. If that is the case destructor should gets called twice.

Could somebody explains me about this behavior?. May be I am missing something obvious.

2

There are 2 answers

0
M.M On BEST ANSWER

A a = A(1); is equivalent to A a = 1;. However, in both cases, copy elision may occur: The A(1) is actually constructed directly into a, instead of being constructed separately and then copied or moved.

It's up to the compiler to decide whether or not to perform copy elision in any of its permitted scenarios (as described in the above link).

1
user657267 On

Your compiler is eliding the copy for A a = 1, but not for A a = A(1);, gcc is able to elide the copy in both cases, this can be tested with -fno-elide-constructors.