mercredi 27 janvier 2016

How to properly forward unique_ptr?

What is generally the proper way to forward an std::unique_ptr?

The following code uses std::move, which I thought was the considered practice, but it crashes with clang.

class C {
   int x;
}

unique_ptr<C> transform1(unique_ptr<C> p) {
    return transform2(move(p), p->x); // <--- Oops! could access p after move, compiler-dependant
}

unique_ptr<C> transform2(unique_ptr<C> p, int val) {
    p->x *= val;
    return p;
}

Is there a more robust convention than simply making sure you get everything you need from p before transferring ownership to the next function via std::move? It seems to me using move on an object and accessing it in the same function call could be a common mistake to make.

Aucun commentaire:

Enregistrer un commentaire