Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the return of this method getting destructed?

Tags:

c++

#include<iostream>
using namespace std;
class mini
{
  public:
  mini() { cout << "mini()";  }
  ~mini() { cout << "~mini()"; }
};
class test
{
  public:
  mini ret()
  {
    return *(new mini());
  }
};
int main()
{
  test a;
  a.ret();
  cout << "end of block";
}

Output:

mini()~mini()end of block

Why is ~mini() run here before the end of the block? Or rather at all... If I change the output of the method to mini* then it doesn't get removed. I understand stack objects do get deleted, but I'm new'ing here.


1 Answers

Consider what happens here

  mini ret()
  {
    return *(new mini());
  }

ret() is a function returning mini by-value.

new mini() allocates mini on the heap. return *(new mini()); returns a copy of it by-value. So what is printed is the construction of mini on the heap and a destruction of its copy on the stack at the end of the full-expression where ret() is called.

To visualize it, implement a copy constructor:

#include<iostream>
using namespace std;
class mini
{
public:
    mini() { cout << "mini()\n"; }
    mini(const mini&) { cout << "mini() copy\n"; }
    ~mini() { cout << "~mini()\n"; }
};
class test
{
public:
    mini ret()
    {
        return *(new mini());
    }
};
int main()
{
    test a;
    a.ret();
    cout << "end of block\n";
}

Prints

mini()
mini() copy
~mini()
end of block

So you're right, the original new'd mini is never deleted (leaked).

like image 105
rustyx Avatar answered Dec 10 '25 23:12

rustyx