6

The following piece of code compiles and runs without errors and with the expected output:

#include <string>
#include <iostream>
using namespace std;

string getString()
{
    char s[] = "Hello world!";
    return s;
}

int main()
{
    cout << getString() << endl;
}

My question is, will this always work? Ordinarily if you return a C-string that was declared locally you can run into some undefined behavior, but in this case is that still a problem since it is run through the string constructor and (presumably) copied into dynamic memory?

3
  • One of the main reason std::string added to standard library - it can be used as an embedded type like int and double, so yes it is fine to return std::string by value. Commented Aug 1, 2017 at 17:24
  • 1
    Did you know that string litterals have static storage duration: cpp-ref. So if your c-string just point to a string literral like in const char* s="Hello World" you can safely return it from your function, since s is a pointer to an object with static storage duration. This is why std::except::what() or type_info::name() return a c-string Commented Aug 1, 2017 at 21:41
  • @Oliv that's a neat fact but this is just an example, in my real program the C string is created at runtime Commented Aug 2, 2017 at 13:40

1 Answer 1

13
 return s;

That line is equivalent to:

return std::string(s);

And that will make a copy of the string, so it's fine.

reference: http://en.cppreference.com/w/cpp/string/basic_string/basic_string (constructor #5)

Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s.

Edit: One more detail. You mention

copied into dynamic memory?

And the answer is maybe, perhaps, it doesn't really matter.

The semantics provided by std::string make no specification towards this, it just guarantees that it can be copied/moved around and accessed in a consistent matter. How it acheives this is up to the library implementor.

In fact, popular implementations of std::string use something called the "Small String Optimization". Where strings under a certain length are stored within the string object itself.

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

3 Comments

The temporary std::string object that is returned is constructed (not copied!) from the array s.
I think you are misinterpreting, the constructor of std::string copies the content of the string pointed by s. s is still a string, a c string, but a string nonetheless.
Yes, fair enough. There's no denying that "a copy of the string" is made, in the sense that the string's bytes will be copied.

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.