0

When I use the std container in c++, I find a funny part I cant understand, anybody can help? The second class contain a container of first class, when the second class creat a local object and push it into container, it will die when outside the function, but it still have one worked in the container and there is only one constructor work, but two destructor work, why????

The first class is:


#include <iostream>

using namespace std;

class Test1{
    private:

    public:

        Test1(){

            cout << "this is in." << endl;
        };

        ~Test1(){

            cout << "this is out." << endl;
        };

        void thiswork(){

            cout << "he is still working" <<  endl;
        }

};

The second class is:

#include "test1.hh"
#include <vector>

using namespace std;

class Test2{

    public:

        Test2(){

            cout << "this is test2 creat." << endl;
        };

        ~Test2(){

            cout << "this is test2 die" << endl;
        };

        void init(){

            Test1 first;
            test2.push_back(first);
            cout << "into vector" << endl;
            test2[0].thiswork();
        };

        void dummy(){

            cout << "into dummy" << endl;
            test2[0].thiswork();
        };
    private:

        vector<Test1> test2 = {};
};

test code:

#include "test2.hh"

int main(){


    Test2 test = Test2();

    test.init();

    test.dummy();

    return 0;
}

surprisingly result:

this is test2 creat.
this is in.
into vector
he is still working
this is out.
into dummy
he is still working
this is test2 die
this is out.

1 Answers1

2

A few hidden rules you missed here:

  1. When you pass an element to push_back member function of std::vector it creates a new object via a copy (or move) constructor (and use the newly created object as an element)
  2. Provided you don't have any move operations manually defined, any C++ class has a copy constructor synthesised on demand.

Thus, in order to properly inspect lifecycle of objects inside of a standard container, you have to do that with help of the copy (or move) constructor:

Test1(const Test1&){
    std::cout << "this is in." << '\n';
};

~Test1(){
    std::cout << "this is out." << '\n';
};
The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49
  • So if this is not a standard container, I need to mannualy create a copy function to copy a new object to the container? – KEIFTH YANG Mar 06 '23 at 16:02
  • @KEIFTHYANG if your class doesn't have any special logic on how it handles its resources, you can get use of default copy constructors, which makes a memberwise copy for you. (commonly it means, that if you don't have any member pointers or references, implicit copy constructor should be enough) – The Dreams Wind Mar 06 '23 at 17:21