容器中c++类的局部对象的生命周期?[重复]

k4ymrczo  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(109)

此问题在此处已有答案

C++ implicit copy constructor for a class that contains other objects(5个答案)
Conditions for automatic generation of default/copy/move ctor and copy/move assignment operator?(3个答案)
3天前关闭。
当我在c++中使用std容器时,我发现一个有趣的部分我不明白,有人能帮忙吗?第二个类包含第一个类的容器,当第二个类创建一个局部对象并将其推入容器时,它会在函数之外死亡,但它仍然有一个在容器中工作,只有一个构造函数工作,但有两个析构函数工作,为什么????
第一类是:

#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;
        }

};

第二类是:

#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 = {};
};

测试代码:

#include "test2.hh"

int main(){

    Test2 test = Test2();

    test.init();

    test.dummy();

    return 0;
}

令人惊讶结果:

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.
64jmpszr

64jmpszr1#

这里有几条你没注意到的潜规则:
1.当你把一个元素传递给std::vector的成员函数push_back时,它会通过复制(或移动)构造函数创建一个新的对象(并把新创建的对象用作元素)
1.假设你没有手动定义任何移动操作,任何C++类都有一个按需合成的复制构造函数。
因此,为了正确地检查标准容器中对象的生命周期,必须借助复制(或移动)构造函数:

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

~Test1(){
    std::cout << "this is out." << '\n';
};

相关问题