【发布时间】: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