Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to return an std::string that local to a function

In C++ what is the best way to return a function local std::string variable from the function?

std::string MyFunc() {     std::string mystring("test");     return mystring;  }  std::string ret = MyFunc(); // ret has no value because mystring has already gone out of scope...??? 
like image 335
Tony The Lion Avatar asked Oct 20 '10 10:10

Tony The Lion


People also ask

How do I return a local string from a function in C++?

Try this: std::string * sp; std::string func() { std::string s("bla"); sp = &s; return s; } int main() { std::string s = func(); if(sp == &s) std::cout << "YAY"; else std::cout << "BOO"; } -- On my compiler (VS) It prints YAY.

How a function can return string?

Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string. All forms are perfectly valid. Note the use of const , because from the function I'm returning a string literal, a string defined in double quotes, which is a constant.

What std::string built in function can return the length of a string?

std::string::length Returns the length of the string, in terms of bytes. This is the number of actual bytes that conform the contents of the string, which is not necessarily equal to its storage capacity.

What does std::string end () return?

std::string::end Returns an iterator pointing to the past-the-end character of the string. The past-the-end character is a theoretical character that would follow the last character in the string.


2 Answers

No. That is not true. Even if mystring has gone out of scope and is destroyed, ret has a copy of mystring as the function MyFunc returns by value.

like image 93
Chubsdad Avatar answered Oct 13 '22 15:10

Chubsdad


There will be a problem if your code is like:

std::string& MyFunc() {     std::string mystring("test");     return mystring; } 

So, the way you've written it is OK. Just one advice - if you can construct the string like this, I mean - you can do it in one row, it's sometimes better to do it like this:

std::string MyFunc() {     return "test"; } 

Or if it's more "complicated", for example:

std::string MyFunct( const std::string& s1,                      const std::string& s2,                      const char* szOtherString ) {     return std::string( "test1" ) + s1 + std::string( szOtherString ) + s2; } 

This will give a hint to your compiler to do more optimization, so it could do one less copy of your string (RVO).

like image 35
Kiril Kirov Avatar answered Oct 13 '22 15:10

Kiril Kirov