简体   繁体   中英

Should I be passing unique_ptr<T> by reference here?

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.

The old code wasn't just "moving" pointers: it keeped the a member inside the structure.

Try something like this:

void func(std::unique_ptr<X>& x){
    auto old_a = x->a;

    x = new X;

    x->a = old_a;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM