0

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?

  • 2
    You didn't assign a reference. You assigned a value (and copy-assigned a `std::string` in the process). Once bound, you can't change a reference. – WhozCraig Aug 27 '16 at 07:43
  • 1
    That's not how it works, your reference remains valid because string f is copied into string m that was passed to Foo by reference – user Aug 27 '16 at 07:43

1 Answers1

2

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

KostasRim
  • 2,053
  • 1
  • 16
  • 32
  • @hvd is it more clear now ? Thank you for your comment – KostasRim Aug 27 '16 at 08:13
  • So as another example, if I have a different class instead of the string class that doesn't overloads the = operator, m would becomes invalid? – StackOverflowUser Aug 27 '16 at 08:14
  • @StackOverflowUser it depends on how the class definition. If, for example, the string class consists of `char* ` which are dynamically allocated on the heap then yes there will be a problem because the copy will be a `shallow copy` (since the overload assignment operator is not defined) . `shallow copy` is a pointer copy, once the object goes out of scope and the `destructor` is called the pointers will point to an invalid memory location (undefined behavior) – KostasRim Aug 27 '16 at 08:18
  • Pointers and references are exactly the same thing, only different syntax. – rustyx Aug 27 '16 at 08:18
  • Thank you. I understand now. – StackOverflowUser Aug 27 '16 at 08:20
  • 1
    @RustyX no they are not, pointer has a valid memory location, references do not. If `a` is a reference to `b` then `a` is just an `alias` of b. `a` does not `reside` in memory. If `a` is a pointer to `b` it exists in a memory location. – KostasRim Aug 27 '16 at 08:20