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

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -