C++内存管理:RAII,智能指针和GC
C++ Memory Management: RAII, Smart Pointers and GC
以下是我对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.
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 优先顺序:智能指针和类析构函数
- 对于C++中使用智能指针的指针算术限制,有没有一种变通方法
- 智能指针作为无序映射键,并通过引用进行比较
- 智能指针概念所有权和寿命
- 正在理解智能指针,但出现错误:未分配正在释放的指针
- 尝试使用智能指针时引发异常
- 我可以制作指向智能指针的智能指针吗?
- 通过智能指针和转换对基本模板参数进行模板推导
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 从堆栈分配的原始指针构造智能指针
- 初始化指向类实例的智能指针并访问其方法
- 如何使用 std::make_shared 创建基类类型的智能指针?
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 编译器不会使用 -std=c++11 编译智能指针
- 具有智能指针的多态性
- C++:矢量分配器行为、内存分配和智能指针
- 在什么情况下,需要共享智能指针而无法使用唯一指针?
- 指向函数签名中的常量智能指针
- 使用智能指针附加的继承对象的深层复制