C++内存管理:RAII,智能指针和GC

C++ Memory Management: RAII, Smart Pointers and GC

本文关键字:智能 指针 GC RAII 内存 管理 C++      更新时间:2023-10-16

以下是我对C++Memeory管理的看法,请随时发表评论。

内存可以在堆栈中分配。

规则 1:

如果两个嵌套堆栈需要共享数据,请使用 RAII 在堆栈中分配内存,如下所示:

func1() {
    Resource res;  // res will be destructed once func1 returns
    func2( &res );
}  

规则 2:

如果两个并行堆栈需要共享数据(不是类成员字段),则必须使用智能点或 GC 在中分配内存。例如:

func() {
    shared_ptr<Resource> res = func1();   // returned a shared ptr to a memory allocated in func1
    func2( res );
}

我说的对吗?

我的观点是你是对的,(我想并行堆栈意味着多线程)

在第一种情况下也可以使用 scoped_ptr(boost)或 unique_ptr(c++11)。在这种情况下,对象在内存heap中分配,而不是stack 。RAII 还会在示波器完成后释放该内存。

shared_ptr是一种引用计数机制,因此,如果其他对象保留shared_ptr(在您的情况下:func2 ),并且在func范围完成后未释放它,则对象shared_ptr仍然可用。

No.您的示例 2 最好写成

void func() {
    Resource res = func1();   // func1 returns a Resource
    func2( res ); // func2 uses that Resource.
}