C++学习笔记-对象生命周期

对象生命周期是指对象从创建到销毁的整个过程。理解对象生命周期对于避免内存泄漏、悬空指针和其他内存相关问题至关重要。

基本的对象生命周期

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

class Entity
{
public:
    Entity() { std::cout << "Create Entity!" << std::endl; }
    ~Entity() { std::cout << "Destroy Entity!" << std::endl; }
};

int main()
{
    {
        Entity e1;  // 在栈上创建的对象离开作用域后会自动销毁
        std::cout << "Inside scope" << std::endl;
    }  // e1在这里被自动销毁
    
    std::cout << "Outside scope" << std::endl;
    
    Entity* e2 = new Entity();  // 堆上创建的对象不会自动销毁
    // delete e2;  // 需要手动删除,否则内存泄漏
}

输出:

Create Entity!
Inside scope
Destroy Entity!
Outside scope
Create Entity!

栈对象的生命周期

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class StackExample
{
private:
    std::string m_Name;
public:
    StackExample(const std::string& name) : m_Name(name)
    {
        std::cout << "Create " << m_Name << std::endl;
    }
    
    ~StackExample()
    {
        std::cout << "Destroy " << m_Name << std::endl;
    }
};

void Function()
{
    StackExample obj1("Function Object");
    
    if (true)
    {
        StackExample obj2("Block Object");
        std::cout << "Inside if block" << std::endl;
    }  // obj2在这里被销毁
    
    std::cout << "After if block" << std::endl;
}  // obj1在这里被销毁

int main()
{
    std::cout << "Before function call" << std::endl;
    Function();
    std::cout << "After function call" << std::endl;
}

堆对象的生命周期

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class HeapExample
{
private:
    std::string m_Name;
public:
    HeapExample(const std::string& name) : m_Name(name)
    {
        std::cout << "Create " << m_Name << std::endl;
    }
    
    ~HeapExample()
    {
        std::cout << "Destroy " << m_Name << std::endl;
    }
    
    const std::string& GetName() const { return m_Name; }
};

int main()
{
    HeapExample* obj1 = new HeapExample("Heap Object 1");
    HeapExample* obj2 = new HeapExample("Heap Object 2");
    
    std::cout << "Objects created" << std::endl;
    
    delete obj1;  // 手动销毁obj1
    std::cout << "obj1 deleted" << std::endl;
    
    // obj2没有被删除,会造成内存泄漏
    
    return 0;
}  // 程序结束,obj2仍然没有被销毁

自动内存管理

实现一个简单的智能指针

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 实现一个简单的智能指针,可以自动释放
class AutoDeletePtr
{
private:
    Entity* m_EntityPtr;
public:
    AutoDeletePtr(Entity* entity) : m_EntityPtr(entity) {}

    ~AutoDeletePtr()
    {
        delete m_EntityPtr;
        std::cout << "AutoDeletePtr destroyed, entity deleted" << std::endl;
    }
    
    Entity* Get() const { return m_EntityPtr; }
    Entity* operator->() const { return m_EntityPtr; }
    Entity& operator*() const { return *m_EntityPtr; }
};

int main()
{
    {
        AutoDeletePtr ptr(new Entity());
        std::cout << "Using smart pointer" << std::endl;
    }  // ptr离开作用域,自动删除Entity
    
    std::cout << "Smart pointer scope ended" << std::endl;
}

使用标准库智能指针

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <memory>

class ManagedEntity
{
private:
    std::string m_Name;
public:
    ManagedEntity(const std::string& name) : m_Name(name)
    {
        std::cout << "Create " << m_Name << std::endl;
    }
    
    ~ManagedEntity()
    {
        std::cout << "Destroy " << m_Name << std::endl;
    }
    
    void DoSomething() const
    {
        std::cout << m_Name << " is doing something" << std::endl;
    }
};

int main()
{
    {
        // unique_ptr自动管理内存
        std::unique_ptr<ManagedEntity> ptr1 = std::make_unique<ManagedEntity>("Unique Entity");
        ptr1->DoSomething();
        
        // shared_ptr允许共享所有权
        std::shared_ptr<ManagedEntity> ptr2 = std::make_shared<ManagedEntity>("Shared Entity");
        {
            std::shared_ptr<ManagedEntity> ptr3 = ptr2;  // 共享所有权
            ptr3->DoSomething();
            std::cout << "Reference count: " << ptr2.use_count() << std::endl;
        }  // ptr3销毁,但对象仍然存在
        
        std::cout << "Reference count: " << ptr2.use_count() << std::endl;
        ptr2->DoSomething();
    }  // 所有智能指针销毁,对象自动删除
    
    std::cout << "All smart pointers destroyed" << std::endl;
}

容器中对象的生命周期

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <vector>

class ContainerElement
{
private:
    int m_Value;
public:
    ContainerElement(int value) : m_Value(value)
    {
        std::cout << "Create element " << m_Value << std::endl;
    }
    
    ContainerElement(const ContainerElement& other) : m_Value(other.m_Value)
    {
        std::cout << "Copy element " << m_Value << std::endl;
    }
    
    ContainerElement(ContainerElement&& other) noexcept : m_Value(other.m_Value)
    {
        std::cout << "Move element " << m_Value << std::endl;
    }
    
    ~ContainerElement()
    {
        std::cout << "Destroy element " << m_Value << std::endl;
    }
    
    int GetValue() const { return m_Value; }
};

int main()
{
    {
        std::vector<ContainerElement> vec;
        
        std::cout << "--- Adding elements ---" << std::endl;
        vec.emplace_back(1);  // 直接在容器中构造
        vec.emplace_back(2);
        vec.emplace_back(3);
        
        std::cout << "--- Vector operations ---" << std::endl;
        ContainerElement elem(4);
        vec.push_back(elem);  // 拷贝构造
        vec.push_back(ContainerElement(5));  // 移动构造
        
        std::cout << "--- Vector size: " << vec.size() << " ---" << std::endl;
    }  // vector销毁,所有元素自动销毁
    
    std::cout << "Vector destroyed" << std::endl;
}

成员对象的生命周期

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Component
{
private:
    std::string m_Name;
public:
    Component(const std::string& name) : m_Name(name)
    {
        std::cout << "Create component: " << m_Name << std::endl;
    }
    
    ~Component()
    {
        std::cout << "Destroy component: " << m_Name << std::endl;
    }
};

class CompositeObject
{
private:
    Component m_Component1;  // 成员对象
    Component m_Component2;
    Component* m_Component3; // 指针成员
    
public:
    CompositeObject() 
        : m_Component1("Component1"), m_Component2("Component2")
    {
        m_Component3 = new Component("Component3");
        std::cout << "Create CompositeObject" << std::endl;
    }
    
    ~CompositeObject()
    {
        delete m_Component3;  // 手动删除指针成员
        std::cout << "Destroy CompositeObject" << std::endl;
    }
    // 注意:成员对象的析构顺序与声明顺序相反
};

int main()
{
    {
        CompositeObject obj;
        std::cout << "CompositeObject created" << std::endl;
    }  // obj销毁,成员对象按相反顺序销毁
    
    std::cout << "CompositeObject destroyed" << std::endl;
}

静态对象的生命周期

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class StaticExample
{
private:
    std::string m_Name;
public:
    StaticExample(const std::string& name) : m_Name(name)
    {
        std::cout << "Create static: " << m_Name << std::endl;
    }
    
    ~StaticExample()
    {
        std::cout << "Destroy static: " << m_Name << std::endl;
    }
};

StaticExample g_GlobalObject("Global");  // 全局对象

void Function()
{
    static StaticExample s_LocalStatic("Local Static");  // 局部静态对象
    std::cout << "Function called" << std::endl;
}

int main()
{
    std::cout << "Main started" << std::endl;
    
    Function();
    Function();  // 局部静态对象只创建一次
    
    std::cout << "Main ending" << std::endl;
    return 0;
}  // 程序结束时,静态对象按创建顺序的相反顺序销毁

异常安全和RAII

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Resource
{
private:
    std::string m_Name;
public:
    Resource(const std::string& name) : m_Name(name)
    {
        std::cout << "Acquire resource: " << m_Name << std::endl;
    }
    
    ~Resource()
    {
        std::cout << "Release resource: " << m_Name << std::endl;
    }
};

class RAIIExample
{
private:
    Resource m_Resource;
public:
    RAIIExample(const std::string& name) : m_Resource(name) {}
    
    void DoWork()
    {
        std::cout << "Doing work..." << std::endl;
        // 如果这里抛出异常,析构函数仍会被调用
        // throw std::runtime_error("Something went wrong");
    }
};

int main()
{
    try
    {
        RAIIExample example("Important Resource");
        example.DoWork();
    }
    catch (const std::exception& e)
    {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }
    // 即使发生异常,Resource也会被正确释放
    
    std::cout << "Program continues" << std::endl;
}

最佳实践

1. 优先使用栈对象

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
void GoodPractice()
{
    // 好的做法:使用栈对象
    Entity entity;
    entity.DoSomething();
    // 自动销毁,无需担心内存管理
}

void BadPractice()
{
    // 不好的做法:不必要的堆分配
    Entity* entity = new Entity();
    entity->DoSomething();
    delete entity;  // 容易忘记
}

2. 使用智能指针管理动态内存

1
2
3
4
5
6
7
void ModernPractice()
{
    // 现代C++做法:使用智能指针
    auto entity = std::make_unique<Entity>();
    entity->DoSomething();
    // 自动管理内存
}

总结

  1. 栈对象:离开作用域时自动销毁,是最安全的内存管理方式
  2. 堆对象:不会自动销毁,需要手动delete,容易导致内存泄漏
  3. RAII原则:资源获取即初始化,利用对象生命周期自动管理资源
  4. 智能指针:现代C++推荐使用智能指针自动管理动态内存
  5. 成员对象:按声明顺序构造,按相反顺序析构
updatedupdated2025-09-202025-09-20