If you swap c strings, is there memory swapping?

Suppose we have:

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

      

If the internal representation of string_class is string c, what happens to memory allocation when values ​​are replaced? For example, say string_class does allocate char* c_str_s1 = new char[5]

, but char* c_str_s2 = new char[10]

(because, say, after 5, the size is doubled). If we do something like std::swap(c_str_s1, c_str_s2)

, is this the memory allocated for each from the sw line, or the minimum allocation assigned to each?

+3


source to share


2 answers


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



+3


source


When you change std::string

s, they internally exchange fields, including pointers char*

, no allocation is done.



EDIT I missed the point that you are not using std::string

s, but you should still be doing this.

+2


source







All Articles