[英]vector<string> or vector<shared_ptr<string>> in c++ 14
In old c++ style, I always used vector < shared_ptr < string> >
or vector < string* >
to avoid memory copy when constructing a big vector
which holds many string
objects. 在旧的c ++样式中,我总是使用
vector < shared_ptr < string> >
或vector < string* >
来避免在构造包含许多string
对象的大vector
时进行内存复制。
Since c++11, c++ has rvalue
and move
semantics; 从c ++ 11开始,c ++具有
rvalue
和move
语义; can I use vector < string >
now? 我现在可以使用
vector < string >
吗?
I am using gcc 7.1.0 and clang 3.6 with the c++ 14 option. 我使用gcc 7.1.0和clang 3.6与c ++ 14选项。
There are several situations where using vector<shared_ptr<string>>
or vector<string*>
could help to optimize performance before C++11: 在以下几种情况下,使用
vector<shared_ptr<string>>
或vector<string*>
可以帮助在C ++ 11之前优化性能:
std::string
has non-throwing move constructor, so in push_back() for std::vector<string>
should be not slower then for std::vector<std::shared_ptr<string>>
. std::string
具有非抛出移动构造函数,因此对于std::vector<string>
push_back()应该std::vector<std::shared_ptr<string>>
慢。 std::vector<string>
is appropriate too. std::vector<string>
也是合适的。 If your intention is to return copy of the collection but not to copy the elements - that is the only way where std::vector<shared_ptr<string>>
can still help. 如果你的目的是返回集合的副本而不是复制元素 - 这是
std::vector<shared_ptr<string>>
仍然std::vector<shared_ptr<string>>
的唯一方法。 But in this case my advice is to share immutable objects between collections, ie use std::vector<shared_ptr<const string>>
. 但在这种情况下,我的建议是在集合之间共享不可变对象,即使用
std::vector<shared_ptr<const string>>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.