Can methods that return const reference or referen

2019-06-15 20:52发布

问题:

I am extremely curious if returning a reference from a method can cause a memory leak. Below is the example situation.

class example
{
public:
  vector<int> & get_vect()
  {
     return vect;
  }
  int & get_num()
  {
    return num;
  }
private:
  vector<int> vect;
  int num;
};


void test_run(example & input)
{ 
   int & test_val = input.get_num();
   vector<int> & test_vect = input.get_vect();
}

int main()
{
  example one;
  test_run(one);
  return 0;
}

My question is when test_val and test_vect get removed from the stack when test_run exits. Does either test_vect or test_val get deleted thereby causing the object one to get corrupted?

回答1:

No. References are aliases (or names) for something else. You can think of it as a never-owning pointer to something without pointer semantics (and their pitfalls, though references themselves have a few twists).

When the function test_run exits, the references and only them are gone. What they referred to hasn't been touched memory-wise, it hasn't been deleted.

Moreover, as you're only dealing with variables that have automatic storage duration and don't involve dynamic memory during construction, you simply can't have memory leaks there. You could have other problems like trying to delete a pointer that points to such variable (trying that just yielded a core dump on coliru) but not leaks.



回答2:

No. Why should it cause a memory leak, if you are not allocating memory with new, which means on the heap? All your variables are allocated on the stack. References are just aliases for other variables.

C++ reference definition according to wikipedia:

The definition of a reference in C++ is such that it does not need to exist. It can be implemented as a new name for an existing object.

There's also a paragraph talking about the difference between pointers and references.