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...???
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.
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With