简体   繁体   English

我应该通过 unique_ptr<t> 在这里参考?</t>

[英]Should I be passing unique_ptr<T> by reference here?

I originally found some (nasty) code to update a pointer to a pointer, doing this:我最初发现了一些(令人讨厌的)代码来更新指向指针的指针,这样做:

void func(X** ptr2ptr, X* oldx){

    X* x2 = new X();
    x2->a(oldx->a);
    // etc

    delete *ptr2ptr;
    *ptr2ptr = x2;
    oldx = *ptr2ptr;
}

as you can imagine, this is horrible.你可以想象,这太可怕了。

I refactored the above method and called it from an outside wrapper, followed by another method which uses the updated pointer (see below).我重构了上面的方法并从外部包装器调用它,然后是另一个使用更新指针的方法(见下文)。 However, it seems my update memory is getting deleted prior to the call to anotherMethod() because I get a seg fault:但是,似乎我的更新 memory 在调用 anotherMethod() 之前被删除了,因为我遇到了段错误:

void wrapper(std::unique_ptr<X>& x){
    func(x);
    anotherMethod(x);
}

void func(std::unique_ptr<X>& x){
    std::unique_ptr<X> x2(new X());
    // same assignment as before

    x = std::move(x2);
}

void anotherMethod(std::unique_ptr<X>& x){
    // Seg fault occurs here whilst accessing x class member
}

Can anybody please help?有人可以帮忙吗? I thought I was doing the correct thing using std::move() and passing the unique_ptr by reference.我认为我正在使用 std::move() 并通过引用传递 unique_ptr 来做正确的事情。

The old code wasn't just "moving" pointers: it keeped the a member inside the structure.旧代码不仅仅是“移动”指针:它将a成员保留在结构中。

Try something like this:尝试这样的事情:

void func(std::unique_ptr<X>& x){
    auto old_a = x->a;

    x = new X;

    x->a = old_a;
}

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

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