c++11 - Should I be passing unique_ptr<T> by reference here? -
i found (nasty) code update pointer 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 can imagine, horrible.
i refactored above method , called outside wrapper, followed method uses updated pointer (see below). however, seems update memory getting deleted prior call anothermethod() because 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 before x = std::move(x2); } void anothermethod(std::unique_ptr<x>& x){ // seg fault occurs here whilst accessing x class member }
can please help? thought doing correct thing using std::move() , passing unique_ptr reference.
the old code wasn't "moving" pointers: keeped a
member inside structure.
try this:
void func(std::unique_ptr<x>& x){ auto old_a = x->a; x = new x; x->a = old_a; }
Comments
Post a Comment