Me gustaría almacenar una referencia a un objeto como weak_ptr. En C++ puro, las siguientes obras:boost :: python y weak_ptr: cosas que desaparecen
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
using namespace std;
using namespace boost;
struct Empty
{
Empty(){}
};
struct Store
{
weak_ptr<Empty> value;
Store(){};
void setValue(shared_ptr<Empty> v) {
cout << "storing " << v << endl;
this->value = weak_ptr<Empty>(v);
shared_ptr<Empty> v_ok = this->value.lock();
if (v_ok) {
cout << "ok, v has been stored" << endl;
}
}
shared_ptr<Empty> getValue() {
shared_ptr<Empty> p = this->value.lock();
if (p) {
cout << "stored value : " << p << endl;
} else {
cout << "there's nothing here !" << endl;
}
return p;
}
};
int main()
{
shared_ptr<Empty> e(new Empty);
shared_ptr<Store> st(new Store);
st->setValue(e);
st->getValue();
return 0;
}
compilar y ejecutar esto le dará la siguiente:
%> ./a.out
storing 0x8c6c008
ok, v has been stored
stored value : 0x8c6c008
Ahora, si yo encapsular que con el impulso de pitón:
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/python.hpp>
#include <boost/weak_ptr.hpp>
using namespace std;
using namespace boost;
using namespace boost::python;
struct Empty
{
Empty(){}
};
struct Store
{
weak_ptr<Empty> value;
Store(){};
void setValue(shared_ptr<Empty> v) {
cout << "storing " << v << endl;
this->value = weak_ptr<Empty>(v);
shared_ptr<Empty> v_ok = this->value.lock();
if (v_ok) {
cout << "ok, v has been stored" << endl;
}
}
shared_ptr<Empty> getValue() {
shared_ptr<Empty> p = this->value.lock();
if (p) {
cout << "stored value : " << p << endl;
} else {
cout << "there's nothing here !" << endl;
}
return p;
}
};
BOOST_PYTHON_MODULE (test)
{
class_< Empty, shared_ptr<Empty> >("Empty");
class_< Store, shared_ptr<Store> >("Store")
.def("get",&Store::getValue)
.def("set",&Store::setValue);
}
y ahora un pequeño script de python para probarlo
from test import *
e = Empty()
st = Store()
st.set(e)
st.get()
... y el resultado es ...
storing 0x9eb2a18
ok, v has been stored
there's nothing here !
lo que al parecer mientras estoy todavía en el mismo método (setValue), no hay problema al recuperar un shared_ptr de Tienda :: valor. Pero tan pronto como salgo de este contexto, ¡ya no queda nada!
¿Cómo puede ser esto? ¿Python está pasando un nuevo (e inútil) shared_ptr como un argumento para setValue, que luego se destruye al final de la llamada? Estoy perdido aquí.
Hmm ... Agregue un destructor a 'Vacío' que imprima un mensaje y vea si se destruye. Además, ¿qué ocurre si almacena un 'shared_ptr'? –
Supongo que en una ubicación 'shared_ptr' se refiere a' :: boost :: shared_ptr' y en otra se refiere a ':: std :: shared_ptr'. Prefiero usar 'typedef' para extraer nombres de espacios de nombres dispares y tener múltiples declaraciones' using namespace'. – Omnifarious
¿Piensas que está relacionado con esto? http://mail.python.org/pipermail/cplusplus-sig/2009-November/014981.html – HostileFork