Is it possible to set an object to null?

前端 未结 5 1900
一个人的身影
一个人的身影 2020-12-01 07:39

Further in my code, I check to see check if an object is null/empty.

Is there a way to set an object to null?

5条回答
  •  被撕碎了的回忆
    2020-12-01 07:59

    You want to check if an object is NULL/empty. Being NULL and empty are not the same. Like Justin and Brian have already mentioned, in C++ NULL is an assignment you'd typically associate with pointers. You can overload operator= perhaps, but think it through real well if you actually want to do this. Couple of other things:

    1. In C++ NULL pointer is very different to pointer pointing to an 'empty' object.
    2. Why not have a bool IsEmpty() method that returns true if an object's variables are reset to some default state? Guess that might bypass the NULL usage.
    3. Having something like A* p = new A; ... p = NULL; is bad (no delete p) unless you can ensure your code will be garbage collected. If anything, this'd lead to memory leaks and with several such leaks there's good chance you'd have slow code.
    4. You may want to do this class Null {}; Null _NULL; and then overload operator= and operator!= of other classes depending on your situation.

    Perhaps you should post us some details about the context to help you better with option 4.

    Arpan

提交回复
热议问题