Search code examples
c++scopereferencereturnstorage-duration

Is it ok to return a variable or object by reference in C++?


So i'm curious whether or not its ok to pass a variable or an object by reference from one file to another in C++ like in the examples below.

String example:

int main() {
  //
  std::cout << GetName() << std::endl;
}

std::string name = "Paul";

std::string& GetName() {
  return name;
}

Object example:

int main() {
  //
  std::cout << GetEmployee().GetAge() << std::endl;
}

Employee employee;

Employee& GetEmployee() {
  return employee;
}

Solution

  • Yes, the above works, but is not commonly used. It works only because in your case the objects whose address you return are static. The following will not work:

    std::string& GetName() {
      std::string name = "Paul";
      return name;
    }
    

    Note that the compiler might let you do this, however since the variable name is allocated on the stack, its address points to unallocated stack space after the method has ended, and accessing it will cause undefined behavior.