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

时间:2015-04-17 01:55:27

标签: c++ memory-management garbage-collection smart-pointers

以下是我对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 );
}

我说错了吗?

2 个答案:

答案 0 :(得分:0)

我的意见是你是对的,(并行堆栈意味着我认为是多线程的)

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

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

答案 1 :(得分:0)

没有。您的示例2更好地写为

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