Search code examples
c++objectnullptr

What is the best practice to check if an object is null in C++


I am working on a simple example. Let s say that I have an object Object my_object and I want to check if the object is null.

Therefore, I instantiate the object:

auto my_object = createMyObject(param_object_1);

The idea, is to check whether the object is null or not. If I am not mistaken (I am really new in C++), I have tried

Check if reference is NULL

I believe this is not an option (even if compiling) since references can never be NULL, so I have discarded it.

EXPECT_TRUE(my_object != NULL);

Check if != to nullptr

My next try has been to check if a pointer to the object is null.

auto my_object_ptr = std::make_shared<Object>(my_object);
EXPECT_TRUE(my_object_ptr != nullptr);

This code also compiles but I am not sure if this is the solution I was looking for. My intentions is to check if the pointer is pointing to a null object.

Is it a valid way to do it? If not, what s the best practise to check if the object is empty?


Solution

  • I want to check if the object is null.

    Congratulations, your Object object is not null. null is not a possible value for object to be.

    A close analog might be to test that it is different to a default-constructed Object, if Object is default-constructable.

    EXPECT_TRUE(my_object != Object{})