Std :: string the capacity remains the same after deleting the elements, is it true while holding some memory?

The following code snippet:

string a = "abc";
cout << a.capacity();
a.erase(a.begin() + 1, a.end());
cout << a.capacity();

... Outputs:

33

Even if I remove some elements from the row, the capacity will remain the same. So my questions are:

  • Is any memory stored due to capacity? What if I don't explicitly reserve()'d?

  • If I use reserve()and do not use the full capacity, am I losing memory?

  • Should this extra memory (which I do not use) be allocated for something else, if necessary?

EDIT: Suppose y <

 string a= "something";
 a = "ab";

Now I know that athere will be no more than two characters. So is it wise to invoke reserve(2)so that memory is not wasted?

+4
source share
2 answers

1) - - ? , () 'd?

, std::string - 1 ( ) std::string. std::string ,

2) std:: reserve() ?

, , ; std::string , . , Short String Optimized std::string . .

3) , , - , ?

. std::string 2 . .

EDIT: ,

string a= "something";

, . a.reserve(2) , ?

a , a.size(), , 2, 2 .

, . std::string::reserve . . std::string::reserve(new_capacity_intended) new_capacity_intended , size() , , , std::string::shrink_to_fit.

( shrink_to_fit) :

string a= "something";
//resize it first
a.resize(2);  //or by some assignment such as a = "so";

//then
a.reserve(2); // or better still a.shrink_to_fit();

1:

2: std::string::reserve std::string::shrink_to_fit .

-1

:

  • , . , . , .

  • .

  • 1): . . . .

string::reserve.

: , , . , , ( ). .


: reserve . reserve(n), , n. , reserve n n (. reserve ).

: reserve, . , . ( ++ 11, shrink_to_fit).

( ) gcc/clang, a 2. 100%, , :

auto a = string{"something"};
a = "ab";
cout << a << " " << a.capacity() << endl;
a.reserve(2);
cout << a << " " << a.capacity() << endl;

:

ab 9
ab 2
+6

Source: https://habr.com/ru/post/1665588/


All Articles