Zhen Zhang Zhen Zhang - 1 month ago 8
C++ Question

Difference between "destroy" "destructor" "deallocate" in std::allocator?

In C++

std::allocator
, there are three methods relating to a common concept:


  • deallocate

  • destroy

  • destructor



I want to know:


  1. How are they different from each other from the memory management perspective?

  2. when should I use this but not that?



Thank you!




Edit: More specific doubts:

I am sorry to generalize it at first, here are some points I don't understand.


  1. What does destructor do? The documentation didn't talk about whether the memory will be released automatically when the destructor is called

  2. The
    destroy
    is used to call the destructor on a object, what does the "object" here means?



Thank you again!

Answer

Just the brief descriptions from the cppreference.com documentation explain the differences very clearly for me

enter image description here

"1. What does destructor do? The documentation didn't talk about whether the memory will be released automatically when the destructor is called"

Any memory occupied by the std::allocator instance will be released as usual.

"2. The destroy is used to call the destructor on a object, what does the "object" here means?"

Again to cite the detailed documentation

 void destroy( pointer p ); // 1)
 template< class U >        // 2)
 void destroy( U* p );

Calls the destructor of the object pointed to by p
1) Calls ((T*)p)->~T()
2) Calls p->~U()

Object in this context means an object of type T managed by the std::allocator instance.

Comments