NULL pointer is the same as deallocating it?

前端 未结 11 2564
一个人的身影
一个人的身影 2021-02-18 18:29

I was working on a piece of code and I was attacked by a doubt: What happens to the memory allocated to a pointer if I assign NULL to that pointer?

For instance:

11条回答
  •  自闭症患者
    2021-02-18 19:02

    This is a classic leak. As you say, the memory remains allocated but nothing is referencing it, so it can never be reclaimed - until the process exits.

    The memory should be deallocated with delete - but using a smart pointer (e.g. std::auto_ptr or boost::shared_ptr (or tr1::shared_ptr) to wrap the pointer is a much safer way of working with pointers.

    Here's how you might rewrite your example using std::auto_ptr:

    std::auto_ptr a( new MyClass() );
    
    /*...do something in the meantime...*/
    
    a.reset();
    

    (Instead of the call to reset() you could just let the auto_ptr instance go out of scope)

提交回复
热议问题