StackOverflowUser StackOverflowUser - 3 months ago 8
C++ Question

Will this reference become invalid?

I am trying to understand reference.

So given the following program...

void Foo(std::string& m)
{
std::string f = "Foo Stack Content";
m = f;
}

int main()
{
std::string m = "Main Stack Content";
Foo(m);

std::cout << m << std::endl;
}


Since m is assigned f in Foo, and f is created on the stack in Foo, when Foo exits, f and the memory it points to won't be valid anymore. Does that mean that m is also invalid now?

Answer

In c++ class, operators can have different meanings depending on the way they were defined(overloaded). In your case m is a reference and f is variable. The expression m = f is an assignment between two class objects(well references are not exactly objects but alias). std::string performs a deep copy between m and f. That means that the values of f are copied to m. You should also keep in mind that there is a fundamental difference between a pointer and a reference. Pointers are real variables that are stored in memory. References are alias, they are the same variable with a different name