简体   繁体   English

C++ 存储容器元素的指针

[英]C++ store pointer of element of container

In my application, I have a std::list<TreeNode> that is the owner of my tree nodes.在我的应用程序中,我有一个std::list<TreeNode> ,它是我的树节点的所有者。 Now I want to be able to access the left and right neighbor inside a TreeNode, so which smart pointer should I use to store the neighbors inside a TreeNode?现在我希望能够访问 TreeNode 内的左右邻居,那么我应该使用哪个智能指针将邻居存储在 TreeNode 内? The only pointer suitable for this is a raw pointer because a TreeNode is not the owner of its neighbors, so I hardly see how a smart pointer could be useful here.唯一适合这种情况的指针是原始指针,因为 TreeNode 不是其邻居的所有者,所以我几乎看不到智能指针在这里有什么用处。

Also, the TreeNodes have to be store in other containers for fast access (to have the highest-priority one), so I can't just store unique_ptr of neighbors, because I also need to store them in fast containers (priority_queue)此外,必须将 TreeNode 存储在其他容器中以便快速访问(以获得最高优先级的容器),所以我不能只存储 unique_ptr 的邻居,因为我还需要将它们存储在快速容器中(priority_queue)

so which (smart) pointer should I use to store the neighbors inside a TreeNode?那么我应该使用哪个(智能)指针将邻居存储在 TreeNode 中?

You should use a suitable pointer type.您应该使用合适的指针类型。

The only pointer suitable for this is a raw pointer唯一适用于此的指针是原始指针

Well, there you go.好吧,给你 go。 If the raw pointer is the only suitable one, then using an unsuitable smart pointer would be counter-productive.如果原始指针是唯一合适的指针,那么使用不合适的智能指针将适得其反。


If you have trouble establishing correct lifetime for the nodes, then shared ownership is something that may be considered.如果您无法为节点建立正确的生命周期,那么可以考虑共享所有权。 An easy choice is to use shared pointers throughout.一个简单的选择是始终使用共享指针。 If you instead want to keep the ownership primarily in a list, then you could use weak pointers elsewhere.如果您想将所有权主要保留在列表中,那么您可以在其他地方使用弱指针。


But I want to use smart pointers because they are the way to go in modern C++但我想使用智能指针,因为它们是现代 C++ 中 go 的方式

You've misunderstood the point of smart pointers.您误解了智能指针的意义。

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

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