在 C++ 中创建或访问时引用取消引用的 NULL 指针是否会产生 UB

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

我正在尝试实现这样的代码

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

假设 get_obj_ptr() 可以 return 指向有效对象的有效指针或 NULL。这段代码在 C++ 中合法吗?如果 prt == NULL 是未定义的行为,则访问 obj,但仅定义 NULL 解引用引用是否也会导致 UB?

是的,唯一的重点是舒适和风格的主题,但理论主题也很重要。也许还有其他优雅和 UB-。无异常和无提升的解决方案?

Is this code legal in C++?

不,这是不合法的。

just defining NULL-dereferenced reference also result into UB?

是的。

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

优雅的解决方案:检查是否为空后绑定引用:

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