jeudi 25 juin 2015

Why destructor is not getting called for anonymous objects?

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.

Aucun commentaire:

Enregistrer un commentaire