简体   繁体   中英

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.

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).

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM