简体   繁体   English

向量 <string> 或矢量 <shared_ptr<string> &gt;在c ++中14

[英]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 ++具有rvaluemove语义; 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之前优化性能:

When you add elements to a vector, eg calling push_back(). 向向量添加元素时,例如调用push_back()。

  • Old behaviour: If vector capacity isn't large enough, the internal memory buffer will be reallocated and all the old objects will be copied to a new buffer. 旧行为:如果向量容量不够大,将重新分配内部内存缓冲区,并将所有旧对象复制到新缓冲区。
  • C++11 behaviour: If vector element type has non-throwing move constructor, then it is called instead of copy constructor. 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>>慢。

When returning a vector that is a local variable from a function 从函数返回作为局部变量的向量时

  • Old behaviour: in case of returning a local variable from a function or method the result is copied. 旧行为:如果从函数或方法返回局部变量,则复制​​结果。 In some limited number of cases compiler is allowed to perform Return Value Optimisation - allocate the object directly on the stack on the caller. 在一些有限的情况下,允许编译器执行返回值优化 - 直接在调用者的堆栈上分配对象。
  • C++11 behaviour: if the return value is rvalue, the move constructor of the vector is called. C ++ 11行为:如果返回值是rvalue,则调用向量的移动构造函数。 This operation is actually very cheap (just swapping two pointers). 这个操作实际上非常便宜(只需交换两个指针)。 So for int this case using std::vector<string> is appropriate too. 所以对于int,这种情况下使用std::vector<string>也是合适的。

Sharing strings between different vectors 在不同向量之间共享字符串

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM