The answer to your question lies in the relationship between the delete operation and the object's destructor.
deallocate (pointer p, size_type size)
- calls "delete p"; - "delete" implicitly calls the destructor of the object at p; - frees/deallocates the memory where the object pointed by p was stored
destroy (pointer p)
- calls only the destructor ((T*)p)->~T() - the memory at addres p will not be freed/deallocated
About destructors
- An explicit call to the destructor is not an implicit call to delete on an object called a destructor.
- note: ~ MyClass () {delete this; } is no exception because it generates an access violation.
Why does it make sense to call the destructor without using delete?
a dynamically allocated object may have pointers to the selected objects as member variables. If you want to free this memory without deleting the original object that contains the pointers that you call, override the destructor, because by default this will not be done.
In the following example, I will try to trivialize the indicated problem.
Example:
template < class T,class U > class MyClass{
private: T* first_pointer; U* second_pointer; public: MyClass(){ //constructor: first_pointer=new T(); //allocate memory for pointer variables second_pointer=new U(); //with non-argument constructors T() and U() } ~MyClass(){ //destructor is overriden delete first_pointer; //because the default-destructor delete second_pointer; //will not release the memory allocated for } //first_pointer and second_pointer void set_first(const T& val){ first_pointer=new T(val);
} void set_second (const U & val) { second_pointer=new U(val);
} }; void some_function (void) { MyClass *; object = new MyClass();//: 00123A // , "first_pointer" // "second_pointer", "". // . object-> ~ MyClass();// addres 00123A - // first_pointer second_pointer // . // , - object-> set_first (T (...))// object-> set_second (U (...))// T U. // - // delete ;// , , // first_pointer second_pointer. // "00123A", } >Now back to std :: allocator and destroy () vs deallocate ()
allocator is an abstraction (interface) for allocating memory. He separates excretion from destruction, liberation from destruction.
destroy () - "destroys" the data in the memory cell, which makes the object unusable, but the memory still exists for use (the object can be built again)
deallocate () - "frees" the memory location in which the object was located, so the storage is not suitable for building the object in this place again. enter the code here
source share