Kraken
Kraken

Reputation: 24213

std::String resizing doesnt change address

I wanted to check that if my string resized, will the address of string change or not. So I wrote the below program whereby initial capacity was 1, and then it changed to 30, I'd assume that on capacity change the string would've moved addresses, but that didnt happen.

Can someone explain why that is?

string s = "1";
string& s1 = s;
cout << &s  << " capacity is " << s.capacity() << endl;
cout << &s1 << endl;

s = "sdhflshdgfljasdjflkasdfhalsjdf";
cout << &s  << " capacity is " << s.capacity() << endl;
cout << &s1 << endl;

Output is

0x7ffc11fc08d0 capacity is 1                                                                                                           
0x7ffc11fc08d0                                                                                                                         
0x7ffc11fc08d0 capacity is 30                                                                                                          
0x7ffc11fc08d0                                                                                                                         

Upvotes: 2

Views: 147

Answers (1)

Jesper Juhl
Jesper Juhl

Reputation: 31475

The string variable will not move, but the buffer it holds a pointer to internally may move to a new address as it allocates more memory. This is not observable by taking the address of the variable though. If you print the pointer returned by the .data() member (by casting it to a void pointer) you may see a change (assuming the new size is enough to trigger reallocation - many strings use a small string optimization with a pre-allocated buffer, so you need to grow beyond that).

Upvotes: 6

Related Questions