存储指针向量的最佳C ++ 11方法 [英] best c++11 way to store a vector of pointers
问题描述
我要存储std::threads
当前,我将其实现为std::vector<std::thread*>
但是,这需要手动删除std::thread
s
Currently, I implemented it as std::vector<std::thread*>
However, this requires manually deleting the std::thread
s
最优雅的c ++ 11方法是什么?我可以看到std::shared_ptr
,但这不是一个过分的杀伤力吗?指针是唯一的,但是std::vector
需要临时复制它们.
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.
也许我不需要指针,但是std::thread
是不可复制的,我想是.
Maybe I do not need pointers, but std::thread
being non copyable, I think I do.
谢谢!
推荐答案
自C ++ 11起,vector
仅要求其值是可移动的,就像thread
一样.因此vector<thread>
应该可以满足您的需求.
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.
如果确实需要存储不可移动的类型(例如,mutex
),则unique_ptr
可能是最佳选择;或不需要移动其值的容器,例如deque
或list
.
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.
这篇关于存储指针向量的最佳C ++ 11方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!