1
我最初发现了一些(讨厌)代码的指针更新的指针,这样做:我应该在这里通过引用传递unique_ptr <T>?
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。
Extrain代码...'oldx = * ptr2ptr'? – EFenix