Question

J'ai un shared_ptr et un weak_ptr

typedef boost::weak_ptr<classname> classnamePtr;
typedef boost::shared_ptr<x> xPtr;

comment convertir un weak_ptr à un shared_ptr

shared_ptr = weak_ptr;
Xptr = classnameptr; ?????
Était-ce utile?

La solution

Comme nous l'avons dit

boost::shared_ptr<Type> ptr = weak_ptr.lock(); 

Si vous ne voulez pas une exception ou utilisez simplement le constructeur cast

boost::shared_ptr<Type> ptr(weak_ptr);

Cela jeter si le pointeur faible a déjà été supprimé.

Autres conseils

Vous ne convertit pas un weak_ptr à un shared_ptr que cela irait à l'encontre tout le but de l'utilisation weak_ptr en premier lieu.

Pour obtenir un shared_ptr d'une instance d'un weak_ptr, lock d'appel sur le weak_ptr.
Habituellement, vous procédez comme suit:

weak_ptr<foo> wp = ...;

if (shared_ptr<foo> sp = wp.lock())
{
    // safe to use sp
}
boost::shared_ptr<Type> ptr = weak_ptr.lock(); // weak_ptr being boost::weak_ptr<Type>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top