Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ string uses maximum buffer allocated?

Tags:

c++

string

stl

I declare a variable string s;

and do s = "abc"; now it has buffer of 3 characters.

After

s = "abcd" it has a buffer of 4 characters.

Now after the third statement

s = "ab" question is will it keep the buffer of 4 characters or will it reallocate a 2 character buffer?

If it will allocate 2 character buffer is there any way I can tell it to keep the allocated maximum buffer.

So does it keep the buffer of maximum size ever allocated ?

s = "ab"
s="abc"
s="a"
s="abcd"
s="b"

Now it should keep a buffer of size 4.

Is that possible?

like image 970
Vivek Goel Avatar asked Jul 28 '11 12:07

Vivek Goel


1 Answers

The string will keep its buffer once it is allocated, and only reallocate if its needs an even larger buffer. It will also likely start with an initial buffer size larger than 3 or 4.

You can check the allocated size using the capacity() member function.


After James' comments below I still believe my answer is correct for the examples given in the question.

However, for a reference counted implementation a sequence like this

s = "some rather long string...";

std::string t = "b";
s = t;

would set s.capacity() to be equal to t.capacity() if the implementation decides to share the internal buffer between s and t.

like image 67
Bo Persson Avatar answered Sep 22 '22 23:09

Bo Persson