且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用于资源管理的C ++ shared_ptr与unique_ptr

更新时间:2023-11-13 14:06:46

当拥有 owning 指针时,像shared_ptrunique_ptr这样的智能指针是很好的工具.
但是对于非所有指针,即观察指针,使用原始指针就可以了.

Smart pointers like shared_ptr and unique_ptr are a good tools when you have owning pointers.
But for non-owning pointers, i.e. observing pointers, using a raw pointer is just fine.

在您的设计中,我认为资源管理器是资源的唯一所有者",因此您可以在资源管理器内部简单地使用某种形式的智能指针 .例如,如果您的Resource类被设计为可正确存储在std::vector中,则资源管理器可以将std::vector<std::unique_ptr<Resource>>作为数据成员,甚至可以使用更简单的std::vector<Resource>.

In your design, I think the resource manager is the only "owner" of the resources, so you could simply have some form of smart pointer inside the resource manager. For example, the resource manager can have a std::vector<std::unique_ptr<Resource>> as a data member, or even a simpler std::vector<Resource> if your Resource class is designed to be correctly storable in a std::vector.

然后,资源管理器可以仅向外部提供非所有者的观察指针,原始指针(或C ++引用)在这种情况下就可以了.

Then, the resource manager can give to the outside just non-owning observing pointers, and raw pointers (or C++ references) are fine for this case.

当然,重要的是资源管理器的生存期必须超过资源客户端"的生存期.

Of course, it's important that the lifetime of the resource manager exceeds that of the "resource clients".