简体   繁体   English

RAII和shared_ptr之间的关系是什么?

[英]what is the relation between RAII and shared_ptr?

I understood the concept of RAII (Resource acquisition is initialization). 我理解RAII的概念(资源获取是初始化)。 It basically says that resources should be reclaimed in destructor to avoid any memory leaks. 它基本上说应该在析构函数中回收资源以避免任何内存泄漏。 But I didn't understand how shared_ptr is a type of RAII. 但我不明白shared_ptr是一种RAII。 Because shared_ptr doesn't guarantee that the pointer will be deleted at the end of the stack. 因为shared_ptr不保证指针将在堆栈末尾被删除。 Deletion is purely dependent on the counter. 删除完全取决于计数器。 So how it is related to RAII? 那么它与RAII有什么关系呢?

std::shared_ptr<T> extends RAII to resources with multiple ownership. std::shared_ptr<T>将RAII扩展为具有多个所有权的资源。 Rather than having to figure out yourself when to delete a shared object, you take a shared pointer down, letting it destroy a shared object, but only when it is the last reference. 您不必弄清楚何时删除共享对象,而是将共享指针放下,让它破坏共享对象,但仅限于它是最后一个引用。

It is helpful not to think of the object pointed to by a shared pointer as an object owned by that shared pointer object. 不将共享指针指向的对象视为该共享指针对象拥有的对象是有帮助的。 Instead, one could think of it as collectively owned by all shared pointers pointing to it. 相反,人们可以认为它是由指向它的所有共享指针共同拥有的。 The resource acquired by the shared pointer object is not only the object itself, but also its reference counter. 共享指针对象获取的资源不仅是对象本身,还是其引用计数器。 Releasing the object is an equivalent of decreasing the reference counter, with the caveat that once the reference count drops to zero, and additional operation of deleting the object must follow. 释放对象相当于减少引用计数器,但需要注意的是,一旦引用计数降为零,就必须执行删除对象的其他操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM