If I do the following:
string* create_array(){
string* arr = new string[2];
string s = "hello";
string s2 = "world";
arr[0] = s;
arr[1] = s2;
return arr;
}
is the assignment of arr[0] = s making a copy of s and then putting that copy in the memory address that arr[0] points to? or is it making arr[0] refer to the local stack variable s, and in this case if I use the array returned from this function calling arr[0] will have unpredictable behaviour?
Thanks
Yes.
No.
arr[0]is astring, it doesn’t point to anything. (internally, it probably has achar*somewhere, but that’s unique per instance ofstd::stringand is an implementation detail, I added this comment just to be complete)Nope, it makes a copy.