在现代C ++中使用非智能指针 [英] using non-smart pointers in modern C++
问题描述
短版:
在现代C ++中使用非智能指针有什么可接受的理由吗?
Short Version:
Is there any acceptable reason for using non-smart pointers in modern C++?
长版:
我们有一个包含许多旧C ++代码的巨大产品,现在我们正尝试将其重构为现代C ++时代.连同所有老式代码,到处都是大量的指针(大多数情况下带有SAL注释以提供某种安全感),我想知道我们是否应该将它们全部更改为智能指针,或者是否应保留其中某些原样?
在尝试转换其中一些代码时,我最终得到了一个代码,该代码对于使用智能指针进行的争论很简单.
所以问题是:是否存在过度使用智能指针的问题?
或者换句话说:这些天非智能指针有什么可以接受的情况?
So the question is: is there such a thing as over using smart pointers?
Or in other words: is there any acceptable scenario for non-smart pointers these days?
推荐答案
智能指针( unique_ptr
和 shared_ptr
)应该是OWNING指针(即负责破坏目的).使用它们的底线是,应将由 new
创建的任何对象尽快推送到 unique_ptr
中,以防止内存泄漏.之后, unique_ptr
应该最终被移动:
Smart pointers (unique_ptr
and shared_ptr
) should be OWNING pointers (i.e., responsible for destruction of the object). The bottom line of using them is that any object created by new
should be shoved into a unique_ptr
ASAP, to prevent memory leaks. After that, the unique_ptr
should end up being moved:
- 如果应该共享所有权,则合并为
shared_ptr
, - ,或者如果所有权是由范围(块或对象的生存期)决定的,则进入
unique_ptr
.
版本
应该很少见.如果您的代码在周围传递了非所有者指针,则这些指针应为:
release
s should be rare. If your code passes non-owning pointers around, these should be:
- 原始指针,如果它们可能为
null
,(由get
获取) - 引用(如果它们可能不是
null
)(由get
获取) 如果调用的目的是转移所有权,则按值 -
unique_ptr
s.(在这种情况下,您需要移动它们)
- raw pointers if they may be
null
, (obtained byget
) - references if they may not be
null
, (obtained byget
) unique_ptr
s by value if the aim of the call is transferring ownership. (in which case you'll need to move them)
工厂方法应按值返回 unique_ptr
s.(因此,如果您不分配factory方法的返回值,则会立即取消分配该对象)
Factory methods should return unique_ptr
s by value. (because then, if you don't assign the return value of the factory method, the object is immediately de-allocated)
并查看阿里(Ali)有关处理遗留代码的一些哲学观点的链接的答案.(我完全同意)
And check out Ali's answer regarding links to some philosophical points of handling legacy code. (Which I totally agree on)
这篇关于在现代C ++中使用非智能指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!