Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the destructor called more than the constructor? [duplicate]

Tags:

c++

destructor

In the following code, the destructor is called twice, while the constructor is called only once:

enum TFoo
{
    VAL1,
    VAL2
};

class CFoo
{

public:
    TFoo mf;

    CFoo()
    {
        cout<<"hi c'tor1\n";
        //mf = f;
    }
    CFoo(TFoo f)
    {
        cout<<"hi c'tor2\n";
        mf = f;
    }
    CFoo(TFoo &f)
    {
        cout<<"hi c'tor3\n";
        mf = f;
    }
    ~CFoo()
    {
        cout<<"bye\n";
    }
};

int main()
{
    vector<CFoo> v;
    //v.assign(1, VAL1);
    v.push_back(VAL1);
}

The code outputs:

hi c'tor2
bye
bye

I found a similar question, which mentioned copy constructors, so I added them, but with the same result. Uncommenting the line //v.assign(1, VAL1); also doesn't change anything.

like image 410
qtreez Avatar asked Jan 02 '15 20:01

qtreez


1 Answers

It is initially constructing using the implicit conversion operator between TFoo and CFoo, CFoo(TFoo f), and then using that temporary object to pass it to push_back to construct the object in the container using the default copy constructor or move constructor, depending on whether you are using C++11 (which is not displaying anything). Then the temporary is destroyed and finally the object in the container (with the container itself).

You can see it here or here (C++11) even better.

like image 146
Shoe Avatar answered Sep 17 '22 13:09

Shoe