-
How come this works?
Code:
#include <iostream>
#include <string>
std::string Func()
{
std::string linha;
std::getline(std::cin, linha);
return linha;
}
int main()
{
std::string linha;
linha = Func();
std::cout << linha << std::endl;
}
In function Func(), I'm returning a local variable and the program displays the correct result. I can't figure out why...
Thanks.
-
I suspect the string class has a copy constructor which dupes the string. Much like returning an integer or what not returns a copy (value actually) when you return one.
Quzah.
-
Yeah, it looks normal - you arent returning a reference to the local string after all.
-
That code looks ok to me... i mean it is suppose to return a string...
-
It's the same situation as:
Code:
int func1()
{
return 1; //Returning 1 by value
}
std::string func2()
{
return std::string("Some String"); //Return a copy of std::string("Some String")
}
You're just returning a value. The problem is, as laserlight mentioned, when you try returning a reference or pointer:
Code:
int& func1()
{
int localVariable;
return localVariable; //localVariable won't exist after func1() ends
}
std::string* func2()
{
std::string localString("Some String");
return &localString; //This address will point to nothing when func2() ends
}