オブジェクトへの参照をweak_ptrとして保存したいと思います。純粋なC++、次の作品では:boost :: pythonとweak_ptr:stuffが消える
#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
、私はブーストのpythonであることをカプセル化する場合:今
#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()
私は同じ方法(のsetValue)まだだながら
...そして結果は...
storing 0x9eb2a18
ok, v has been stored
there's nothing here !
はそう明らかに、ストア::値から のshared_ptrを取得する問題はありません。しかし、私がこの文脈から抜け出すとすぐに、何も残っていません!
これはどのようにすることができますか? PythonはsetValueの引数としてブランドの新しい(無用な)shared_ptrを渡していますが、呼び出しの終わりに破棄されますか?私はここで失われています。
Hmm ...メッセージを印刷し、破壊されるかどうかを調べるためのデストラクタを 'Empty'に追加します。また、 'shared_ptr'を保存するとどうなりますか? –
私の推測では、ある場所では 'shared_ptr'は' :: boost :: shared_ptr'を参照し、別の場所では ':: std :: shared_ptr'を参照します。異なる名前空間の名前を複数の 'using namespace'宣言に引き込むために、' typedef'を使うことを大いに好みます。 – Omnifarious
これはこのようなものだと思いますか? http://mail.python.org/pipermail/cplusplus-sig/2009-November/014981.html – HostileFork