Does this code leak memory? (references, new, but

2019-08-22 13:58发布

问题:

Possible Duplicate:
Does using references instead of pointers, resolve memory leaks in C++?

When I ask this question

Does using references instead of pointers, resolve memory leaks in C++?

A new question appears and I ask it in this post.

Does this code leak memory?

class my_class
{
  ...
};

my_class& func()
{
  my_class* c = new my_class;
  return *c;
}

int main()
{
  my_class& var1 = func();

  // I think there is no memory leak.
  return 0;
}

回答1:

Yes, it does leak memory. Everything that was created by new has to be destroyed by delete. There's new in your code, but no delete. That immediately means that the newed memory is leaked.



回答2:

It does create a memory leak. Look at this example:

int main()
{
  my_class var1;
  my_class& var2 = var1;
  ...
}

Here the destructor for var1 will only be called once, if your assumtions were true, it would be called twice.



回答3:

Yes, you have to free every instance of an object u allocated using the 'new' operator or using the 'malloc' function.



回答4:

Make sure you clear the memory by using 'delete' when you are done.