智能指针是 RAII 的良好实践吗?
Is smart pointer a good practice of RAII?
首先,这里讨论 RAII&Smart Pointer。
我一直认为像 shared_ptr
这样的智能指针是 RAII 的一个很好的实践,因为它在像
这样的构造函数中获取堆内存资源
shared_ptr<A> pA(new pA());
并且可以通过引用计数及其析构函数适时释放内存。
然而,今天早上我的同事告诉我:
"smart pointer is not what i thought to be RAII. The only thing that can strictly be called as RAII in the STL is std::lock_guard
, the others are nothing more than RRID. "
我是不是搞错了什么?或者我同事说的实际上是胡说八道?
来自 cppreference:
Resource Acquisition Is Initialization or RAII, is a C++ programming technique which binds the life cycle of a resource that must be acquired before use (allocated heap memory, thread of execution, open socket, open file, locked mutex, disk space, database connection—anything that exists in limited supply) to the lifetime of an object.
std::shared_ptr
绝对是 RAII,因为它获取资源并将其生命周期绑定到自己的生命周期,从而接管 releasing/destructing 资源的责任。这就是RAII的核心原理。
RRID(Resource Release Is Destruction)这个词很少见,其含义似乎有些模糊。大多数情况下它与RAII具有相同的含义。
恕我直言,围绕 RAII 变体的许多讨论都认为过于准确地解释了该术语的含义。 RAII 旨在表示对象生命周期管理的概念。
首先,这里讨论 RAII&Smart Pointer。
我一直认为像 shared_ptr
这样的智能指针是 RAII 的一个很好的实践,因为它在像
shared_ptr<A> pA(new pA());
并且可以通过引用计数及其析构函数适时释放内存。
然而,今天早上我的同事告诉我:
"smart pointer is not what i thought to be RAII. The only thing that can strictly be called as RAII in the STL is
std::lock_guard
, the others are nothing more than RRID. "
我是不是搞错了什么?或者我同事说的实际上是胡说八道?
来自 cppreference:
Resource Acquisition Is Initialization or RAII, is a C++ programming technique which binds the life cycle of a resource that must be acquired before use (allocated heap memory, thread of execution, open socket, open file, locked mutex, disk space, database connection—anything that exists in limited supply) to the lifetime of an object.
std::shared_ptr
绝对是 RAII,因为它获取资源并将其生命周期绑定到自己的生命周期,从而接管 releasing/destructing 资源的责任。这就是RAII的核心原理。
RRID(Resource Release Is Destruction)这个词很少见,其含义似乎有些模糊。大多数情况下它与RAII具有相同的含义。
恕我直言,围绕 RAII 变体的许多讨论都认为过于准确地解释了该术语的含义。 RAII 旨在表示对象生命周期管理的概念。