简体   繁体   中英

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.

Since c++11, c++ has rvalue and move semantics; can I use vector < string > now?

I am using gcc 7.1.0 and clang 3.6 with the c++ 14 option.

There are several situations where using vector<shared_ptr<string>> or vector<string*> could help to optimize performance before C++11:

When you add elements to a vector, eg calling 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. 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>> .

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. This operation is actually very cheap (just swapping two pointers). So for int this case using std::vector<string> is appropriate too.

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. But in this case my advice is to share immutable objects between collections, ie use std::vector<shared_ptr<const string>> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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