What is a dangling pointer?

后端 未结 7 819
心在旅途
心在旅途 2020-11-22 02:48

I know this is pretty common question, but still new for me!

I don\'t understand concept of dangling pointer, was googling around, and writing test methods to find o

7条回答
  •  臣服心动
    2020-11-22 03:43

    As a matter of style, I explain a dangling pointer as "a pointer which still exists, even though the object it pointed to no longer exists".

    In your case, the pointer name exists for a shorter period that the object that it points to. So it's never dangling.

    Inside common C++ classes, pointers dangle for a very short period, inside destructors. That's because the delete statement is before the last } of the destructor, while the pointer itself ceases to exist at the last }. If you don't want to worry about this, use e.g. unique_ptr. The T* pointer will dangle for a very short time inside the unique_ptr::~unique_ptr destructor, which is perfectly safe.

提交回复
热议问题