简体   繁体   中英

Guaranteed allocation size in std::string initialization.\

There are a variety of questions around this topic already on this site:

My question is different from these in that I am interested in how std::string determines its original capacity and how I can rightsize a string assuming that I know how many bytes exactly I will need. Calling reserve(n) can result in the string allocating more memory and I need it to be 24 bytes (right above the sso threshold, can't fit under). Overallocation would be quite dramatic as I potentially hold millions of these in memory, so if it, eg, aligns at 32 bytes the 33% overhead really hurts. Naturally I would also like to avoid the potential reallocation from shrink_to_fit .

My understanding is that you can get an exact allocation size by initializing as std::string(rightsized_constant, size) via the const char*, size_t ctor, but of course nothing guarantees this.

Is there a reasonably clean way to get this using std::string ?

Solution I used after some thinking, discussion with a coworker and brief experiments with clang++/g++ on Linux.

template<typename T>
class Reader {
  void operator()(T key, std::string* append_to);
};
...
Reader a;
Reader b;
std::string s;
std::vector<KeyType> keys = ...;
std::vector<std::string> out;
out.reserve(keys.size());
for (const auto& key : keys) {
  a(key, &s);
  b(key, &s);
  out.emplace_back(s); // relies on assumption that copy will rightsize
  s.clear(); // relies on the implicit guarantee that this doesn't release memory
} // s rightsized after first iteration

Still curious if anything actually gives a guarantee.

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