开发者

Does this code leak memory? (references, new, but no delete) [duplicate]

This question already has answers here: Closed 11 years ago.

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 开发者_StackOverflow社区is no memory leak.
  return 0;
}


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.


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜