Boost.Coroutineのローカル変数の寿命
Boost1.53.0リリースされてましたね。
個人的に気になっているのはCoroutine。
pythonのyeildみたいなことが出来るライブラリ。
ローカル変数の寿命が気になったのでちょいと調べた。
#include <boost/coroutine/coroutine.hpp> #include <iostream> typedef boost::coroutines::coroutine<int()> coroutine_type; class Test{ public: Test(){ std::cout << "Test: constructor" << std::endl; } ~Test(){ std::cout << "Test: destructor" << std::endl; } }; void func(coroutine_type::caller_type &yeild){ Test t; std::cout << "Function: start" << std::endl; for (int i = 0; i < 3; i++){ std::cout << "Function: yield " << i << std::endl; yeild(i); } std::cout << "Function: end" << std::endl; } int main(){ std::cout << "Main: start" << std::endl; coroutine_type c(func); while(c){ std::cout << "Main: get " << c.get() << std::endl; c(); } std::cout << "Main: end" << std::endl; return 0; }
出力は以下
Main: start Test: constructor Function: start Function: yield 0 Main: get 0 Function: yield 1 Main: get 1 Function: yield 2 Main: get 2 Function: end Test: destructor Main: end
ふむふむ、コルーチンのオブジェクト(呼び方あってるか知らんが)の寿命じゃなくて、関数が終わった次点でローカル変数は消えるらしい。
コンパイルも少し手間取った。
libboost_contextをリンクしなければいけない。
(-Iやら-Lは各自補うように)
$ g++ coroutine.cpp -lboost_context