Allocating memory using new returns same memory address

后端 未结 5 889
清酒与你
清酒与你 2021-01-21 08:38
class abc  {
    int x ;
};
int main()
{
    abc *A = new abc ;
    cout<< static_cast(A) << endl ;
    delete A ;
    cout<< static_cast&         


        
5条回答
  •  长情又很酷
    2021-01-21 09:29

    abc *A = new abc ;
    cout<< static_cast(A) << endl ;
    

    This is the first output.

    delete A ;
    cout<< static_cast(A) << endl ;
    

    Though it is after delete the value of A remains the same. What delete did was: 1. call the destructor (in this case trivial) of A and 2. Inform the memory allocator that the memory allocated for A is now free and can be used for other purposes.

    abc *B = new abc ;
    cout<< static_cast(B) << endl ;
    

    It may be that in this step output will be still the same - since allocator has the memory previously allocated for A for use now, it may use it for B.

    delete B ;
    cout<< static_cast(B) << endl ;
    

    The same as before with A.

提交回复
热议问题