为什么stl vector不能包含coroutine对象?

xun*_*ang 2 c++ boost stl coroutine c++11

我在boost1.53中使用coroutine,请参阅下面的代码:

boost::coroutines::coroutine<int()> f(std::bind(foo, ...));
std::vector<decltype(f)> container; // it can be compiled
container.push_back(f); // compile error
Run Code Online (Sandbox Code Playgroud)

错误:

no matching function for call to ‘std::vector<boost::coroutines::coroutine<int(),0> >::vector(paracel::coroutine<int>&)’
Run Code Online (Sandbox Code Playgroud)

更新:错误发生,因为'boost :: coroutines :: coroutine'中没有复制构造/运算符,这里的情况是我只想将'f'保存到将索引映射到'f'的容器中.

我也试过unordered_map和emplace_back,它仍然无法正常工作!

如何使它在C++中工作?

Update2:我尝试了vector,unordered_map,与emplace_back,push_back,std :: move一起映射,并且都失败了.但是list和deque在push_back/emplace_back和std :: move中是可以的:

std::deque<decltype(f)> container1;
container.push_back(std::move(f)); // ok
std::deque<decltype(f)> container2;
container.emplace_back(std::move(f)); // ok
std::list<decltype(f)> container3;
container.push_back(std::move(f)); // ok
std::list<decltype(f)> container4;
container.emplace_back(std::move(f)); // ok
Run Code Online (Sandbox Code Playgroud)

为什么?

Die*_*ühl 8

它看起来好像boost::coroutines::coroutines<int()>不支持复制构造函数.push_back()然而,你尝试了一个左值.您可能想尝试将对象移动到矢量中,但是:

container.push_back(std::move(f));
Run Code Online (Sandbox Code Playgroud)

  • 如果要放入向量中的类型既不可复制也不可移动,则不起作用.你需要使用一个不同的容器,例如`std :: deque <...>`或`std :: list <...>`和`emplace_back()`对象. (4认同)