dimanche 29 novembre 2015

Smart pointer to an object that can change the pointer

I want to have a smart pointer to an object A that has a function f which can change the current object A that the smart pointer should point to. The function should work for all smart pointers and its ideal syntax is this:

//usage of f
std::unique_ptr<A> = p(new A);
p.reset(A->f(p.get()));

Raw pointers are used as argument and return value to make this work with any smart pointer. The flaw in this implementation is self-assignment caused by f returning the same pointer it was given. The self-assignment will result in the deletion of the current instance of A, which is not what we want. To remedy this we could use f like this:

//modified usage of f
std::unique_ptr<A> = p(new A);
A* temp = A->f(p.get());
if(p.get() != temp) {
  p.reset(temp);
}

This requires a temporary raw pointer right next to the smart pointer that might even point to the same object. To me it feels like bad design and I expect there to be a better solution than this.

I've also thought about passing a the smart pointer by reference, but this has some problems:

  • It does not force a return after resetting the smart pointers, which could cause memory corruption.
  • It forces the function to take a specific smart pointer as argument.

Am I overthinking this problem? Is using a temporary raw pointer to check if the smart pointer needs to be reset actually fine? Also, why does the reset function not already check for self-assignment?

Aucun commentaire:

Enregistrer un commentaire