You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++容器中类局部对象的生命周期疑问求助

C++ vector容器对象构造析构问题解答

Test2类的init函数中创建Test1局部对象并推入vector,局部对象销毁后容器内对象仍可正常工作,且运行时仅触发一次Test1构造函数输出,但有两次析构输出,以下是原因分析:

一、局部对象销毁后容器对象仍能工作的原因

当执行test2.push_back(first)时,vector并不会存储局部对象first本身,而是会创建一个first的副本并存储在容器内部。init函数结束后,局部对象first被销毁,但vector中存储的是独立的副本,因此后续调用test2[0].thiswork()可以正常执行。

二、一次构造输出、两次析构输出的原因

你只显式实现了Test1的默认构造函数,而当push_back执行拷贝操作时,编译器会自动为Test1生成一个默认拷贝构造函数——这个编译器生成的拷贝构造函数不会输出任何日志,所以你看不到它的调用记录,但它确实创建了vector中的那个副本对象。

整个流程中实际存在两个Test1对象:

  • 第一个是init函数里的局部对象first,由默认构造函数创建(对应日志this is in.),在init函数结束时销毁(对应第一次this is out.)
  • 第二个是vector中存储的副本对象,由编译器生成的拷贝构造函数创建(无日志输出),在Test2对象销毁时(vector也随之销毁)被析构(对应第二次this is out.)

验证方法

如果显式添加Test1的拷贝构造函数并加上日志,就能看到拷贝构造的过程:

class Test1{
    private:
    public:
        Test1(){
            cout << "this is in." << endl;
        };
        // 显式添加拷贝构造函数
        Test1(const Test1& other) {
            cout << "this is copy in." << endl;
        }
        ~Test1(){
            cout << "this is out." << endl;
        };
        void thiswork(){
            cout << "he is still working" <<  endl;
        }
};

此时运行会输出:

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

这样就能清晰看到两次构造(默认+拷贝)和两次析构的对应关系。


原代码

Test1类代码

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

};

Test2类代码

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

内容的提问来源于stack exchange,提问作者KEIFTH YANG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 05:25:24