c++ - nullptr 是否引用 C++ 中的未定义行为?

标签 c++ reference undefined-behavior nullptr

<分区>

以下代码使用 nullptr 指针和引用来愚弄:

#include <cstdio>

void printRefAddr(int &ref) {
    printf("printAddr %p\n", &ref);
}

int main() {    
    int *ip = nullptr;
    int &ir = *ip;

    // 1. get address of nullptr reference
    printf("ip=%p &ir=%p\n", ip, &ir);

    // 2. dereference a nullptr pointer and pass it as reference
    printRefAddr(*ip);

    // 3. pass nullptr reference
    printRefAddr(ir);

    return 0;
}

问题:在 C++ 标准中,注释语句 1..3 是有效代码还是未定义行为?

这与不同版本的 C++ 相同还是不同(旧版本当然会使用 0 文字而不是 nullptr 关键字)?

额外的问题:是否有已知的编译器/优化选项,这实际上会导致上面的代码执行一些意外/崩溃?例如,是否有任何编译器的标志,它会在初始化引用的任何地方为 nullptr 生成隐式断言,包括从 *ptr 传递引用参数?


好奇的示例输出,没有意外:

ip=(nil) &ir=(nil)
printAddr (nil)
printAddr (nil)

最佳答案

// 2. dereference a nullptr pointer and pass it as reference

取消引用空指针是未定义的行为,因此无论您是将其作为引用还是按值传递,事实是您已经取消引用它并因此调用了 UB,这意味着从那时起所有赌注都取消了。

您已经在此处调用了 UB:

int &ir = *ip; //ip is null, you cannot deref it without invoking UB.

关于c++ - nullptr 是否引用 C++ 中的未定义行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16164106/

相关文章:

c++ - 一旦遇到被归类为未定义行为的构造,是否允许 C++ 编译器发出随机代码?

c++ - "undefined behaviour"是否扩展到编译时?

c++ - C/C++中如何更 pretty-print 调用栈?

reference - C++/CLI 引用未在随后进入本地 block 时初始化为 nullptr

c# - 找不到 Microsoft.Office.Interop.Excel 引用

c++ - 返回对类的引用

c++ - 为什么在我使用模板时 VS 不自动完成?

c++ - GNUPlot 的 MPI IO 格式化

c++ - SIMD/SSE : short dot product and short max value

c - 为什么这些构造使用增量前和增量后未定义的行为?