Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a destructor for a pointer in c++?

Tags:

c++

pointers

string * str=new string;
delete str;

when I delete 'str' which points to an object, do two destructors get called - one for the pointer itself, and one for the object it points to?

What would the pointer's destructor do?

like image 503
jiafu Avatar asked May 08 '13 09:05

jiafu


People also ask

Do smart pointers call destructor?

The smart pointer destructor contains the call to delete, and because the smart pointer is declared on the stack, its destructor is invoked when the smart pointer goes out of scope, even if an exception is thrown somewhere further up the stack.

Do destructors delete pointers?

Default destructors call destructors of member objects, but do NOT delete pointers to objects.

Do you need a destructor with smart pointers?

Boost smart pointers by themselves don't have anything to do with the need for a destructor. All they do is remove the need for you to call delete on the allocated memory that they are effectively managing.

Do pointers have to be deleted?

Pointers to variables on the stack do not need to be deleted. They become invalid on their own when the function the variable is in returns. Pointers to memory created using new should be deleted using delete .


1 Answers

delete just causes the object that the given pointer is pointing at to be destroyed (in this case, the string object. The pointer itself, denoted by str, has automatic storage duration and will be destroyed when it goes out of scope like any other local variable.

Note, however, that non-class types do not have destructors. So even when you use delete with non-class types, no destructor is called, but when the pointer goes out of scope, it gets destroyed as normally happens with any other automatic variable (means the pointer just reaches the end of its lifetime, though the memory pointed to by the pointer is not deallocated until you use delete to explicitly deallocate it.).

like image 182
Joseph Mansfield Avatar answered Nov 15 '22 04:11

Joseph Mansfield