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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With