Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does std::string allocation take place on initialization

When I create a std::string member variable in a class, will there be already a default memory allocated when it is instantiated? Or does std::string defer allocation until it is actually used?

I'm using Visual Studio 2010 at the moment, and I noticed, when I create an empty string with:

  std::string s0;
  std::string s1 = "";

Both have capacity == 15 set. So does this mean that it already allocated 15 bytes of memory? If yes, can I prevent this so that no memory is allocated?

Would this be implementation specific across different compilers?

like image 391
Devolus Avatar asked Mar 15 '23 17:03

Devolus


1 Answers

The initial capacity of an empty std::string is unspecified by the standard, and is implementation dependent.

Many implementations will allocate an initial capacity of around 16 or so characters (and yes, the capacity refers to allocated memory).

like image 108
Sander De Dycker Avatar answered Mar 17 '23 07:03

Sander De Dycker