std::unique_ptr 是 RAII 的应用吗? [英] Is std::unique_ptr an application of RAII?
问题描述
这是对它的准确描述吗?有意义吗?
Is that an accurate description of it? Does it make sense?
你是否保证它指向的对象在 unique_ptr 超出范围之前不会被删除 [即使你没有使用 unique_ptr]?
Are you guaranteed that the object it points to won't be deleted until the unique_ptr goes out of scope [even if you're not using the unique_ptr]?
推荐答案
是的,std::unique_ptr
遵循 RAII 设计原则.
Yes, std::unique_ptr
follows the RAII design principle.
不,std::unique_ptr
不会阻止其他代码做一些愚蠢的事情,比如在属于 unique_ptr
delete>.unique_ptr
本身会在它拥有的对象上调用一个删除器1:
No, std::unique_ptr
does not prevent other code from doing something stupid, like calling delete
on a pointer that belongs to the unique_ptr
. The unique_ptr
itself will call a deleter1 on the object it owns when either:
- 超出范围
或
unique_ptr
被重新分配(通过operator=
或reset
)指向不同的对象
- the
unique_ptr
is reassigned (viaoperator=
orreset
) to point to a different object
还可以通过移动到不同的智能指针或使用 release
成员函数来撤销 unique_ptr
对对象的所有权.这会破坏对象与 unique_ptr
之间的关联,并且 unique_ptr
将不再清理对象.
One can also revoke unique_ptr
's ownership of an object by moving to a different smart pointer, or using the release
member function. This breaks the association between the object and the unique_ptr
and unique_ptr
will no longer clean up the object.
1 默认删除器将使用 delete
或 delete []
,具体取决于目标是否具有数组类型.但是unique_ptr
是一个模板,它的deleter可以自定义,比如FILE*
的清理操作可以选择调用fclose
>.
1 The default deleter will use either delete
or delete []
, depending on whether the target has array type. But unique_ptr
is a template and its deleter can be customized, for example the cleanup operation for a FILE*
can be chosen to be a call to fclose
.
此功能可用于安排在 unique_ptr
超出范围时执行的任意清理操作.RAII 用于保持锁定、关闭文件等——显然,如果仅仅因为编译器没有看到智能指针的任何未来使用而提前执行清理操作,则会出现重大问题.幸运的是,C++ 对象生命周期规则是完全确定的(甚至同一范围内多个自动变量的销毁顺序也有明确定义),并且您可以指望智能指针在智能指针本身被销毁时准确地清理其拥有的对象.
This capability can be used to schedule an arbitrary cleanup action to take place when the unique_ptr
goes out of scope. RAII is used for keeping locks, closing files, and so forth -- clearly there would be major problems if the cleanup action were performed early just because the compiler didn't see any future usage of the smart pointer. Luckily the C++ object lifetime rules are completely deterministic (even the order of destruction for multiple automatic variables in the same scope is well defined), and you can count on the smart pointer cleaning up its owned object exactly when the smart pointer is itself destroyed.
这篇关于std::unique_ptr 是 RAII 的应用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!