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