jwe*_*rek 3 c++ smart-pointers
我一直在思考,虽然我了解std :: observer_ptr的目标,但我认为如果至少有一个类似指针类型的选项(它知道指向的内容是否已被删除)会很好。例如,我们可能会有类似以下内容
slightly_smart_ptr<Foo> p1(new Foo());
auto p2 = p1;
p1.erase(); // This deletes the foo referred to by p1.
if (p2.expired())
std::cout << "p2 is expired\n"; // this will fire
Run Code Online (Sandbox Code Playgroud)
One way to achieve this with the current standard library is to make a shared_ptr to A in some scope that will exist for the lifetime of A, always refer to A by passing weak_ptrs around, and delete A when it is no longer needed by resetting the shared_ptr. The weak_ptrs here will have the basic semantics of observer_ptrs that know if A has been deleted. But there are problems with this approach: weak_ptrs must be locked, turning them into shared_ptrs to be used, which feels untidy, but more seriously a shared_ptr to A must exist somewhere, when all the user wants is a slightly smart pointer that does not own any content. The user agrees to manually destroy the content when it is time: no ownership is shared so it is a code smell for the user to create a shared_ptr in such a situation.
I however cannot think of a way in which the details of this implementation could be effectively hidden.
Also does such a pointer exist as a proposal or in a boost library or elsewhere?
一般来说不可行。
现有智能指针的全部目的是以一种通常无法通过原始指针实现的方式来跟踪对象的生存期和所有权,除非您迷上了分配器并且该分配器与任何与之相关的句柄之间存在复杂的关系到分配的对象。
您所描述的好处是使用上述现成的智能指针所带来的好处。shared_ptr而且weak_ptr在这里很完美。
锁定没有问题(您想要这样做),并且不必有任何问题shared_ptr,因为肯定有某人确实拥有该数据。如果不是这样,您的设计就会遇到更大的问题,并且您正试图使用类似的破坏性智能指针概念来解决这些问题,而该概念在标准中将永远不会存在。
这样的智能指针的问题是,这将是更多的错误比俯卧std::unique_ptr,T*或std::weak_ptr。
当您想知道某个指针的唯一所有者是否已将其从其他位置删除时,实际上您需要共享所有权和std::weak_ptr。
您会看到,有一个原因使您在使用它之前需要“锁定”弱指针。这是因为当您开始使用它时,您获得了指针的所有权。如果您无法锁定知道是否已删除的观察者指针,则无法安全使用它,因为在验证其有效性之后的任何时候都可以将其删除。
另外,您还有更深的矛盾。
当您拥有唯一的指针时,您知道谁将删除它,并且您知道谁是所有者。
如果您有一个检查指针有效性的程序,那是因为您的程序不知道资源的所有权。
如果您的程序不知道资源的所有权,那么您需要共享所有权以在执行代码时推迟所有权决定。
如果您拥有共享所有权,则不需要知道是否已删除的观察者指针。
这样,您的指针就不需要存在。
所以...您以为您需要该指针,它可能很方便...您能做什么?
您需要检查您的代码。如果只有一个所有权,那么为什么需要知道指针的有效性。为什么不能简单地问房主呢?
如果所有者不存在,则删除所有者后,可能要执行检查的代码可能无效。可能要进行检查的结构应该与所有者同时死亡。
如果您的唯一所有者死于不可预测的时刻(例如,您的唯一所有者由共享所有者持有),那么您的结构可能应该改为检查共享所有者的有效性。
也许您的代码调用了要检查其指针是否仍然有效的函数,当所有者死亡时,根本不应该调用它。
...
等等。
有很多方法可以解决此问题,但是在唯一所有者上需要一个弱指针通常会显示程序中的缺陷或程序中对象生命周期的推理问题。
| 归档时间: |
|
| 查看次数: |
138 次 |
| 最近记录: |