简体   繁体   English

传递包装为 unique_ptr C++ 的“this”

[英]Passing 'this' wrapped as unique_ptr C++

I have a class that acts as a node in a binary tree, one of the methods which I would like to call from inside that class is recursive, and needs to pass itself to the next node in the tree so that the next node knows its own parent.我有一个 class 作为二叉树中的一个节点,我想从内部调用的方法之一是 class 是递归的,需要将自身传递给树中的下一个节点,以便下一个节点知道它的自己的父母。 I dont want to store a class member parent because I would like to avoid using a shared_ptr.我不想存储 class 成员父级,因为我想避免使用 shared_ptr。

The code looks something like this:代码看起来像这样:

void MyClass::expand(MyClass* parent){
    for (int i = 0; i < children.size; i ++){
        children[i]->doSomethingWithParent(parent);
        children[i]->expand(this);
    }
    return;
}

But I would like to pass a unique_ptr instead of a raw pointer.但我想传递一个 unique_ptr 而不是原始指针。 However, the pointer to 'this' is already wrapped elsewhere by a unique_ptr already, so I dont want to instantiate another.但是,指向“this”的指针已经被 unique_ptr 包裹在其他地方,所以我不想实例化另一个。 Is it possible to do this?是否有可能做到这一点?

If there are any design patterns I should be aware of please let me know.如果有任何我应该知道的设计模式,请告诉我。

Any help appreciated任何帮助表示赞赏

Don't use a pointer at all.根本不要使用指针。 You are not taking ownership, the argument is not optional, so use a reference:您没有获得所有权,该参数不是可选的,因此请使用参考:

void MyClass::expand(MyClass& parent){
    for (int i = 0; i < children.size; i ++){
        children[i]->doSomethingWithParent(parent);
        children[i]->expand(*this);
    }
    return;
}

All of your code will perform the same, and it is safer etc.您的所有代码都将执行相同的操作,并且更安全等。

If you ever have a situation where you want to pass a non-owning pointer that is guaranteed to be non-null (which appears to be the case here), then you probably want to just use a reference instead.如果您曾经遇到过要传递保证为非空的非拥有指针的情况(这里似乎就是这种情况),那么您可能只想使用引用。

In your case, depending on what doSomethingWithParent performs, you'd probably actually want a const reference as well:在您的情况下,根据doSomethingWithParent的执行情况,您实际上可能还需要一个 const 引用:

void MyClass::doSomethingWithParent(const MyClass& parent) {
  // who knows?
}

void MyClass::expand(const MyClass& parent) {
    for (int i = 0; i < children.size; i ++){
        children[i]->doSomethingWithParent(parent);
        children[i]->expand(*this);
    }
}

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

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