To the best of my understanding, when I declare
String s = "This is a string.";
what happens is that space is allocated on the stack for a pointer which points to some String object which internally contains a char array. My confusion stems from the fact that this pointer seems(I could be wrong) to behave differently than any other type of pointer. For example, if I write
int a = 1;
int* x = &a;
int* y = x;
what happens is that the pointer saved in y now points to the same location in memory as the pointer saved at x. So if I write
String s1 = "This is a string.";
String s2 = "Hello World!";
s1 = s2;
does the pointer saved at s1 now point to the same memory location as s2? Or does s1 copy the char array from s2 into its own separate memory? Further, If I write
String s1 = "This is a string.";
s1 = "Hello World!";
does s1 now point to whatever arbitrary memory location was created for the string literal "Hello World!"? Will this memory location be freed later, or is some sort of smart garbage collector in place which knows that I am using that memory in the heap? Finally, should I never assign a string declared on the stack to a global variable, as this will be referencing a memory location which will be freed soon?
Thank you in advance for your help!
s1 = s2
will invoke the overloaded assignment operator, which will, depending on the used C++ version, execute amove()
or acopy
. Expressions of the forms1 = "Some String value";
will result in a copy (seeoperator = (const char *cstr)
). Also see hackingmajenkoblog.wordpress.com/2016/02/04/…