简体   繁体   English

原始指针管理

[英]Raw pointer management

Is it appropriate for a class to return aa raw pointer in a "create" method and take a raw pointer argument in its "destroy" method? 类是否适合在“创建”方法中返回原始指针并在其“销毁”方法中使用原始指针参数? The aforementioned class stores the pointer in a container and finds/deletes the specified object through the destroy method. 前述类将指针存储在容器中,并通过destroy方法查找/删除指定的对象。

Or should I be using smart pointers? 还是应该使用智能指针? If I understand correctly, smart pointers indicate ownership, but the class is solely responsible for both creation and destruction of the object. 如果我理解正确,智能指针会指示所有权,但是该类仅负责对象的创建和销毁。

The question is: Can you programatically describe the acquire/release behaviour that the code should have? 问题是:您可以以编程方式描述代码应具有的获取/释放行为吗? If yes, ie the behaviour isn't a series of unique events without any pattern, then you can write a handle class that implements this behaviour. 如果是,即行为不是一系列没有任何模式的唯一事件,则可以编写一个实现此行为的句柄类。 Even more, this handle class will be able to guarantee the behaviour, which is what smart pointers are all about. 更重要的是,该句柄类将能够保证行为,这就是智能指针的全部含义。 It's not just about correctness of code, but about extended guarantees that make it easier to write correct code. 这不仅关乎代码的正确性,而且关乎扩展的保证,使编写正确的代码更加容易。

Also, smart pointers don't always indicate ownership, though they do in most cases. 同样,尽管在大多数情况下,智能指针并不总是表示所有权。 There is also a distinction between shared ownership (shared_ptr) and exclusive ownership (auto_ptr, unique_ptr). 共享所有权(shared_ptr)和排他所有权(auto_ptr,unique_ptr)之间也有区别。 Then, there is eg a mere reference without ownership (weak_ptr). 然后,例如存在一个没有所有权的纯引用(weak_ptr)。

To me, it sounds like you might want to return a shared_ptr with an according deleter. 对我来说,听起来您可能想返回带有相应删除器的shared_ptr。 The factory can then eg keep a weak_ptr to retain some access to the according objects, while the shared_ptr guarantees correct cleanup. 然后,工厂可以例如保留weak_ptr以保留对相应对象的某些访问,而shared_ptr保证正确的清理。 Make sure you regularly purge expired weak_ptrs from the factories internals though. 但是,请确保定期从工厂内部清除过期的weak_ptrs。

In no case would I return a raw pointer. 在任何情况下,我都不会返回原始指针。 The question this bears is: What should the caller do with it when they are done? 这带来的问题是:完成后,调用方应如何处理? Call delete? 通话删除? Call some specific destroy() function? 调用一些特定的destroy()函数? Both of these are better handled by a smart pointer. 两者都可以通过智能指针更好地处理。 Also, if the factory retains ownership and reserves itself the right to discard the object at any time, how is the one holding a raw pointer informed about the fact that this pointer will become invalid? 另外,如果工厂保留所有权并保留随时丢弃该对象的权利,那么持有原始指针的人如何得知该指针将变为无效的事实? A simple answer would be to use a smart pointer that gets notified, like eg weak_ptr. 一个简单的答案是使用被通知的智能指针,例如weak_ptr。

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

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