【问题标题】:Should I be passing unique_ptr<T> by reference here?我应该在这里通过引用传递 unique_ptr<T> 吗?
【发布时间】:2016-12-02 13:05:31
【问题描述】:

我最初发现了一些(讨厌的)代码来更新指向指针的指针,这样做:

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

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

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

你可以想象,这太可怕了。

我重构了上述方法并从外部包装器调用它,然后是另一个使用更新指针的方法(见下文)。但是,似乎我的更新内存在调用 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
}

有人可以帮忙吗?我认为我使用 std::move() 并通过引用传递 unique_ptr 是正确的。

【问题讨论】:

  • 提取您显示的代码...oldx=*ptr2ptr ?

标签: c++11 move-semantics unique-ptr


【解决方案1】:

旧代码不仅仅是“移动”指针:它将a 成员保留在结构中。

试试这样的:

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

    x = new X;

    x->a = old_a;
}

【讨论】:

    猜你喜欢
    • 2012-01-13
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 2015-09-25
    • 2014-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多