Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If you're swapping c strings, does the memory allocation also swap?

Tags:

c++

Suppose we have the following:

string_class s1("hello");
string_class s2("goodbye");

If the internal representation of the string_class string is a c string, what happens to memory allocation when you swap the values? For example, let's say string_class allocates char* c_str_s1 = new char[5], but char* c_str_s2 = new char[10] (because, say, after 5 the size doubles). If we do something like std::swap(c_str_s1, c_str_s2), is the memory allocated for each c string swapped, or is minimum allocation given to each?

like image 296
Bob John Avatar asked Dec 02 '25 17:12

Bob John


2 Answers

The pointers are swapped as-they-are: that means each of them after the swap will point to the memory allocated for the other. The contents of memory are not supposed to be changed in any other way.

like image 109
Ashalynd Avatar answered Dec 05 '25 07:12

Ashalynd


When you swap std::strings, they internally exchange fields including char* pointers, no allocation is performed.

EDIT I missed the point that you are not using std::strings, but you should consider doing it anyway.

like image 26
Anton Savin Avatar answered Dec 05 '25 05:12

Anton Savin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!