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:
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.
Aucun commentaire:
Enregistrer un commentaire