Let's say I've got this simple code:
class Foo
{
private:
const char* str;
public:
void Set(const char* c) { str = c; }
const char* Get() const { return str; }
};
Foo f;
void func1()
{
// Please note: Comments of the answer below refer to const char* localStr.
// I posted the wrong code.
const char localStr[] = "Hello world!";
//f.Set(localStr); // Of course, does not work, std::cout prints garbage
f.Set("Hello world!"); // Works
}
int main()
{
func1();
std::cout << "Get: " << f.Get() << std::endl;
}
I'm trying to understand why exactly f.Set("Hello world!");
is working.
For my understanding f.Set(localStr);
of course does not work. When func1()
returns, localStr
goes out of scope and Foo::str
points to garbage.
But what is happening with f.Set("Hello world!");
? I thought that the string argument is also a temporary/local const char[]
which gets passed to Foo::Set
as a pointer (to it's first element). Why is Foo::str
still valid after the call when the passed argument is only a temporary/local?