unique_ptr< int []>或vector< int> ;? [英] unique_ptr<int[]> or vector<int>?
问题描述
如果您不需要动态增长并且在编译时也不知道缓冲区的大小,那么应该何时使用 unique_ptr< int []>
代替 vector< int>
是否全部?
If you don't need dynamic growth and don't know the size of the buffer at compile time, when should unique_ptr<int[]>
be used instead of vector<int>
if at all?
使用 vector
而不是 unique_ptr
?
推荐答案
使用 std :: vector
与 std :: unique_ptr< int []>
不会造成性能损失。但是,替代方案并不完全相同,因为矢量可以增长并且指针不能(矢量可能是优缺点,矢量是否会错误地增长?)
There is no performance loss in using std::vector
vs. std::unique_ptr<int[]>
. The alternatives are not exactly equivalent though, since the vector could be grown and the pointer cannot (this can be and advantage or a disadvantage, did the vector grow by mistake?)
还有其他差异,例如值将在 std :: vector
中初始化的事实,但如果您 new,则不会
数组(除非您使用 value-initialization ...)。
There are other differences, like the fact that the values will be initialized in the std::vector
, but they won't be if you new
the array (unless you use value-initialization...).
在一天结束时,我个人会选择 std :: vector<>
,但是我仍然在C ++ 03中编写代码,而没有 std :: unique_ptr
。
At the end of the day, I personally would opt for std::vector<>
, but I still code in C++03 without std::unique_ptr
.
这篇关于unique_ptr< int []>或vector< int> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!