Saket
Saket

Reputation: 49

does compiler call implicit destructor on an object initialised by new

I have a doubt, as C++ (GNU g++) compiler call implicit d-tor with objects in stack. when it calls d-tor for an object, where memory - allocated with new.

struct abc{
   int a;
};

int main(){
 {
     abc ob1;
 }//! Here implicit ~abc() will be called

 {
 abc *ob2 = new abc();
 } //! Will comipler call d-tor for ob2 ?

 return 0;
}

Please help me to know, if compiler is not release memory of *ob2 then why it is doing like so?

Upvotes: 0

Views: 735

Answers (2)

Chuck Walbourn
Chuck Walbourn

Reputation: 41057

You are not using a smart-pointer and you are not using an explicit delete, so the ob2 object is going to leak.

If, however you use a smart-pointer it will get cleaned up when it leaves scope:

{
    std::unique_ptr<abc> ob2( new abc() );
}

unique_ptr will call delete on the 'owned' object automatically when ob2 leaves scope.

Of course you should really use make_unique instead of calling new explicitly and that's a good place to use C++11 auto as well:

{
    auto ob2 = make_unique<abc>();
}

See Smart Pointers (Modern C++)

In general in Modern C++, you shouldn't be calling delete explicitly in most cases. See the C++ Core Guidelines and in particular:

C.149: Use unique_ptr or shared_ptr to avoid forgetting to delete objects created using new

R.11: Avoid calling new and delete explicitly

ES.60: Avoid new and delete outside resource management functions

Upvotes: 3

GhostfromTexas
GhostfromTexas

Reputation: 169

No. You need to call delete on the object.

If you create an object dynamically in C++ (a non-managed language), you must call delete on the object to free up the memory on the heap.

Calling delete on the pointer to the object will call the destructor of the object you're deleting.

Upvotes: 5

Related Questions