Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ unique pointer: memory leak

I am little confused about release method of unique pointer. Here is my sample program.

class Test
{
public:
    Test(){std::cout << "ctor" << std::endl;}
    ~Test(){std::cout << "dtor" << std::endl;}
};

int main() {
    std::unique_ptr<Test> ptr(new Test());
    ptr.release(); // memory leak
    //ptr.reset(); // this is ok but not necessary
    return 0;
}

Output:

ctor

Since it is not printing dtor i am assuming it is not calling destructor of Test which will lead to memory leak. Is it?

like image 958
Nishant Kumar Avatar asked Jul 04 '14 04:07

Nishant Kumar


1 Answers

The word release means "release ownership to the caller". So no, the destructor isn't called by it.

If you want to call the destructor explicitly then you have to either delete the released pointer manually, or just call reset, which is the preferred way to do it.
If you don't need to do this explicitly then you can just leave it and it'll get taken care of automatically.

like image 170
user541686 Avatar answered Oct 18 '22 15:10

user541686