问题
I want to store a vector of std::threads
Currently, I implemented it as std::vector<std::thread*>
However, this requires manually deleting the std::thread
s
What would be the most elegant c++11 way to do this? I could see std::shared_ptr
, but isn't it an overkill? The pointers are unique, but std::vector
needs to copy them temporarily.
Maybe I do not need pointers, but std::thread
being non copyable, I think I do.
Thanks!
回答1:
Since C++11, vector
only requires that its values are movable, as thread
is. So vector<thread>
should meet your needs.
There are a few restrictions on what you can do with non-copyable types - you can't copy values in or out, only move or emplace them - but these are easy to accommodate.
If you did need to store unmovable types (mutex
, for example), then unique_ptr
is probably the best option; or a container like deque
or list
that doesn't need to move its values.
回答2:
Yoy may use std::vector<std::thread>
and emplace_back
:
threads.emplace_back([](int i){ ++i; }, 10);
emplace_back
uses perfect forwarding to pass its arguments directly to std::thread
constructor, and places new object in vector
internal memory, something like:
new (vector_ptr + offset) std::thread(args...);
It only involves moving - a new semantics of handling objects which is alternative to copying and may be cheaper in terms of resource usage. std::thread
supports moving.
回答3:
use std::unique_ptr if your compiler supports c++11, or boost::shared_ptr if your compiler does not.
No, it is not overkill -- it is good programming.
来源:https://stackoverflow.com/questions/29037929/best-c11-way-to-store-a-vector-of-pointers