Nick
Nick

Reputation: 972

Do reference to dereferenced NULL pointer produce UB on creation or on access in C++

I'm trying to implement code like this

if (auto *ptr = get_obj_ptr(), &obj = *ptr; ptr)
{
    // access obj here
}
else
    // handle error without accessing ptr and obj

assuming that get_obj_ptr() could return either valid pointer to valid object or NULL. Is this code legal in C++? Accessing to obj if prt == NULL is undefined behavior, but do just defining NULL-dereferenced reference also result into UB?

Yes, the only point is the subject of comfort and style, but theoretical subject is also matter. Maybe there is any other elegant and UB-. exception-, and boost-free solution?

Upvotes: 1

Views: 76

Answers (1)

eerorika
eerorika

Reputation: 238351

Is this code legal in C++?

No , it is not legal.

just defining NULL-dereferenced reference also result into UB?

Yes.

Maybe there is any other elegant and UB-. exception-, and boost-free solution?

An elegant solution: Bind the reference after checking for nullness:

if (auto *ptr = get_obj_ptr())
{
    auto& obj = *ptr; 
    // access obj here

Upvotes: 2

Related Questions