0

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

16
  • It is a bad practice to return an array allocated with new from a function. Consider using std::vector or std::array instead. You usually should not mess with raw pointers when you don't sure you need to, or, especially, if you doubt in how they work. Commented Nov 13, 2012 at 14:20
  • @Mikhail I am using arrays over vectors for speed as I am doing some real time image processing stuff. Commented Nov 13, 2012 at 14:22
  • 1
    Not really sure why the question gets a down vote :s Commented Nov 13, 2012 at 14:23
  • @Aly there is no speed difference, std::array should actually be faster. Commented Nov 13, 2012 at 14:25
  • @Let_Me_Be I am definitely seeing a tangible speed difference (albeit microseconds) between raw pointer and vector Commented Nov 13, 2012 at 14:26

1 Answer 1

4

is the assignment of arr[0] = s making a copy of s

Yes.

and then putting that copy in the memory address that arr[0] points to?

No. arr[0] is a string, it doesn't point to anything. (internally, it probably has a char* somewhere, but that's unique per instance of std::string and is an implementation detail, I added this comment just to be complete)

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?

Nope, it makes a copy.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.