Nullptr and checking if a pointer points to a valid object

前端 未结 2 1428
情歌与酒
情歌与酒 2020-12-13 17:10

In a couple of my older code projects when I had never heard of smart pointers, whenever I needed to check whether the pointer still pointed to a valid object, I would alway

2条回答
  •  伪装坚强ぢ
    2020-12-13 18:00

    It's not possible to test whether a pointer points to a valid object or not. If the pointer is not null but does not point to a valid object, then using the pointer causes undefined behaviour. To avoid this sort of error, the onus is on you to be careful with the lifetime of objects being pointed to; and the smart pointer classes help with this task.

    If meh is a raw pointer then there is no difference whatsoever between if (meh) and if (meh != 0) and if (meh != nullptr). They all proceed iff the pointer is not null.

    There is an implicit conversion from the literal 0 to nullptr .

提交回复
热议问题