Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a local C-string for function with C++ string return value

Tags:

c++

string

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?

like image 545
ClydeTheGhost Avatar asked Aug 01 '17 17:08

ClydeTheGhost


People also ask

Which function returns a string within a string?

The function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string.

Can we return string in C++?

Use the std::string func() Notation to Return String From Function in C++ Return by the value is the preferred method for returning string objects from functions. Since the std::string class has the move constructor, returning even the long strings by value is efficient.


1 Answers

 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.

like image 69
Frank Avatar answered Oct 19 '22 05:10

Frank