gpt4 book ai didi

c++ - 单一所有者和多个引用的智能指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:17:37 24 4
gpt4 key购买 nike

回到过去,我使用原始指针实现链表和树。当我尝试使用智能指针实现时,我遇到了以下问题,因为我不知道如何使用只有一个所有者但有 0 个或多个引用的指针:

举一个二叉树的例子:

对于初学者来说,节点应该是指针的唯一“所有者”:节点与树一起生死,所以对我来说,让它们成为 unique_ptr 是有意义的而不是 shared_ptr :

class Tree {
std::unique_ptr<Node> root_;
}

class Node {
std::unique_ptr<Node> left_child_, right_child_;
}

然后我不得不做一个这样的算法:

Node * node = root_.get(); // <-- what type should node be??
while(node) {
if (node->left_count < node->right_count) {
node = node->left_child_.get();
} else {
node = node->right_child.get();
}
}
// do something on node

但我不喜欢使用原始指针。那么什么样的智能指针node应该?这个想法是它不应该拥有指针的所有权。我读到 weak_ptr — 这看起来像我想要的 — 仅适用于 shared_ptr ,但我再次认为不需要 shared_ptr 的开销这里。在任何时候,只有一个所有者。

对于链表也是一样:

class LinkedList {
std::unique_ptr<Node> first_;
/** ?? type ?? **/ last_;
}


for (/*?? type ??*/ n = first_; n != last_; n = n->next) {
}

编辑

我不喜欢使用原始指针(除了在 C++ 中不再使用它们之外)的原因是我想将它们暴露给外部(通过接口(interface)):应该清楚它们不应该被释放。 smart pointer在这里应该是明智的选择。

最佳答案

也许您在这里过度工程。外部客户端使用原始指针应该没问题,只要它们尊重它们不涉及对象生命周期的事实。如果你真的想成为纯粹主义者,那么你需要使用 shared_ptr 并返回 weak_ptr。请注意,您实际上可能需要这样做,因为为了构建或维护您的数据结构,可能需要临时共享内部指针。

另一种选择是在数据结构中使用 unique_ptr 并创建您自己的自定义智能指针,该指针使用 unique_ptr::get 返回的原始指针。我认为一个好的名字应该是 proxy_ptr,甚至可以是这样的:proxy_ptr p = make_proxy(yourUniquePtr.get());

关于c++ - 单一所有者和多个引用的智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23315171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com