Talk about a reference to the memory allocated by new inside the return function

  • 2020-05-10 18:34:13
  • OfStack

I saw a post on bbs: why can't I return a reference to the memory allocated by new within the function?

lz asks:

According to this sentence,


string& foo()
{
string* str = new string("abc");
return *str; 
}

Illegal. Why?

In fact, I can't say that this is illegal, only that this u programming habit is bad, which is likely to cause memory leaks.

And then there was this response:


struct a_s
{
int a;
};

a_s* foo()
{
  struct a_s* sp = new struct a_s;
  return sp;
}

This is good. Why did reference leak out?

I don't think it's a good idea to write like this, because it's the same thing as lz, and I don't think it's a memory leak, but it's a memory leak. To avoid memory leaks when writing code, programmers must ensure that delete is released for every pointer generated with new.

If you do both of these things, even a very careful programmer will inevitably cause a memory leak.

For example, string str = foo(); Obviously, the memory generated by new will not be freed.

Only this:


string& tmp = foo();
string str = tmp; 
delete &tmp;

This will prevent memory leaks. But every time this is who feel annoyed. string str = "hello" + foo(); The above formula causes memory leak unconsciously. So, even careful programmers can't avoid memory leaks.

To prove my idea, I wrote the test code :(vs2008 mode passed)


#include <iostream>
using namespace std;
class example
{
public:
example()
{
  num = new int;
  *num = 10;
  cout<<"num = "<<*num<<endl;
  cout<<" structure "<<endl;
}
~example()
{
  cout<<" destructor "<<endl;
  delete num;
}
void pingfang()
{
  *num *= *num;
}
void print()
{
  cout<<*num<<endl;
}
private:
int *num;
};

example & diaoyong1()
{
example * p = new example;
p->pingfang();
return *p;
}

example * diaoyong2()
{
example * p = new example;
p->pingfang();
return p;
}

int main(void)
{
example & e1 = diaoyong1();
e1.print();
delete &e1;
example * ptr = diaoyong2();
ptr->print();
delete ptr;
getchar();
return 0;
}

The results are as follows:

num = 10
structure
100
destructor
num = 10
structure
100
destructor

According to the operation results, my conclusion is as follows:

This is not to say that the reference or pointer to the memory allocated by the return function new is illegal, just that if you want to return, you must pay 10 points of attention, because there is a high probability of a memory leak. So 1 generally does not advocate returning a reference or pointer to the memory allocated by function memory new.


Related articles: