-
returning std::string
My ? is, can you rely on the (value, pointer to char *, or whatever ) when you return a local std::string?
For instance:
std::string f(std::string first, std::string last)
{
std::string name = first + last;
return name;
}
According to scoping rules, the memory occupied by the std::string variable "name" should be released back to the stack when the function exits. I see A LOT of code out there that does this very thing and the value returned is used later on. Are there special rules regarding std::string?
thank you!
-
As you're returning a std::string object and not a pointer or reference to the one created in the function then a copy of the returned sting will be made when the string is returned to the calling function (assuming you are assigning the return value to a string).
'name' will be out of scope, but 'name' won't be used after the function has returned.
If you are returning a pointer or reference to the string then you cannot rely on the value if the string object was created in the function.
-
-
well heres how i hear it from Bjarne Stroustrupm no not personally but from his book, and i Assume your using MSVC since it has poblems with this very thing.
>
std::string f(std::string first, std::string last)
{
std::string name = first + last;
return name;
}
<
this is perfectly legal and should work,
the compiler should setup a temporary variable to hold string and return it to the requesting variable. see example below
Code:
int func(void)
{
int a = 10;
return a;
}
int main()
{
int k = func();
printf("%d\n",k); // should print 10
return 0;
}
the above should be equivalent in the result NOT IN ACTUALITY to the following
int main()
{
int a = 10;
k = a;
printf("%d\n",k);
return 0;
}