【问题标题】:Return a pointer to pointer to object in C++返回指向 C++ 中对象的指针的指针
【发布时间】:2014-04-02 00:34:47
【问题描述】:

我正在尝试定义一组模板类来表示 C++ 中的搜索树。
find 方法中,我需要返回包含给定键的节点的指针(表示为指针);这样我就复用find方法来实现插入和删除。

template <class K, class R>
struct Node {
    K key;
    R record;

    inline Node(K k, R r) {
        this->key = k;
        this->record = r;
    }
};

template <class K, class R>
struct BST_Node : public Node<K,R> {
    BST_Node<K,R> *sx;
    BST_Node<K,R> *dx;

    inline BST_Node(K key, R record)
    : Node<K,R>(key, record) {
        this->sx = NULL;
        this->dx = NULL;
    }

    BST_Node<K,R> **find(K k) {
        BST_Node<K,R> **p = k < this->key ? &this->sx : &this->dx;

        while (*p && k != (*p)->key)
             p = k < (*p)->key ? &(*p)->sx : &(*p)->dx;

        return p;
    }
/* other methods */
};

只有一个问题:如果密钥在根目录中怎么办?
我无法返回&thisbecause this,我该怎么办?

因为我想使用指向指针的指针是因为这样我可以返回一个 NULL 指针的地址,所以对于插入我可以写这样的东西:

BST_Node<K,R> *insert(K k, R r) {
    BST_Node<K,R> **p = this->find(k);

    if (*p == NULL) //if the search fails
        *p = new BST_Node<K,R>(k, r);

    return *p;
}

【问题讨论】:

  • 为什么一定要返回双指针?
  • 我认为没有必要返回双指针。
  • 帖子编辑的原因是双指针。

标签: c++ pointers binary-tree


【解决方案1】:

你不清楚。 在你的情况下,指针 this 有一个类型

BST_Node<K,R>* const

这意味着你不能改变方向(我不知道如何具体描述它,就像指针指示的地址..)。如果你返回

//BST_Node<K,R>**
return &this;

表示你可以通过返回值改变this的值。这是不允许的。所以发生了错误。

这里为什么要返回双指针?

我看到了你的版本,我想你可以在函数 find() 中返回一个 NULL 来表示你在 root 中找到了密钥。编写递归 find 函数时会有点复杂,但由于您使用的是循环,因此您只需在 find 函数的第一个添加 if 语句即可。在 insert 函数中这样写:

if (p == NULL) //if returns the root
    /*do sth.*/

提示一下,我从不在根目录中保存任何数据,通常当我使用树时,我的树根的寿命将与树一样长。

【讨论】:

  • 感谢您的解释。我编辑了我的帖子,原因是使用双指针。
  • 澄清一下:BST_Node 是一个内部类,我用它来表示“原始”二叉搜索树。无论如何,你的想法很棒,谢谢!
【解决方案2】:

我认为你应该更加仔细地重新阅读笔记。

问题是 &this 位于内存中的某个位置,它指向“您所在的”当前对象(您的代码正在执行的当前对象范围)。
返回 &this 将每次指向您的代码所在的当前对象,这不是您想要的(它实际上取决于编译器,我从未读过编译器的任何“承诺”以在这种情况下返回任何值,它不在 C++ 标准中)

解决方法很简单:

void* tothis = malloc(sizeof(void*)); // allocate memory that will survive leaving the current scope
tothis=this; // copy the current object memory address to the object
return &tothis; // return what you want

之后请不要忘记释放tothis的内存地址(这样就不会泄露)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多