我想存儲一個對象作爲weak_ptr的參考。在純C++,下面的工作:的boost ::蟒蛇的weak_ptr:東西消失
#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;
}
編譯和運行這會給你:
%> ./a.out
storing 0x8c6c008
ok, v has been stored
stored value : 0x8c6c008
現在,如果我封裝與升壓蟒蛇:
#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);
}
現在小python腳本來嘗試一下
from test import *
e = Empty()
st = Store()
st.set(e)
st.get()
......而結果是...
storing 0x9eb2a18
ok, v has been stored
there's nothing here !
如此明顯,而我仍然在同樣的方法(setValue方法),是沒有問題的檢索從商店::值 shared_ptr的。但是,一旦我擺脫這種情況,就什麼都沒有了!
這怎麼可能? python會傳遞一個全新的(無用的)shared_ptr作爲setValue的參數,然後在調用結束時被銷燬?我迷失在這裏。
嗯...添加一個析構函數到'Empty'打印一條消息,看它是否被破壞。另外,如果你存儲'shared_ptr',會發生什麼? –
我的猜測是,在一個位置'shared_ptr'指':: boost :: shared_ptr',而在另一個位置則指':: std :: shared_ptr'。我非常希望使用'typedef'將名稱從不同的名稱空間中提取到具有多個'using namespace'聲明。 – Omnifarious
認爲它與此有關? http://mail.python.org/pipermail/cplusplus-sig/2009-November/014981.html – HostileFork