nullptr引用未定义的行为在C + +? [英] Are nullptr references undefined behaviour in C++?

查看:3411
本文介绍了nullptr引用未定义的行为在C + +?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The following code fools around with nullptr pointer and reference:

#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有效代码或未定义的行为?

Question: In C++ standards, are commented statements 1..3 valid code or undefined behavior?

对于不同版本的C ++,这是相同或不同的(旧的版本当然会使用 0 literal而不是 nullptr 关键字)?

Is this same or different with different versions of C++ (older ones would of course use 0 literal instead of nullptr keyword)?

奖金问题:是否有已知的编译器/优化选项,这实际上会导致上面的代码做某事意外/崩溃?例如,是否有任何编译器的标志,它将生成 nullptr 的隐含断言,其中引用被初始化,包括从 * ptr传递引用参数

Bonus question: are there known compilers / optimization options, which would actually cause above code to do something unexpected / crash? For example, is there a flag for any compiler, which would generate implicit assertion for nullptr everywhere where reference is initialized, including passing reference argument from *ptr?

奇怪,没有什么意外的输出示例:

An example output for the curious, nothing unexpected:

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


推荐答案


2.解除引用一个nullptr指针并将其作为引用传递

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

解除空指针<行为,因此无论您是以引用还是通过值传递它,事实是您已经取消引用它,因此调用UB,意味着从那时起所有投注都将关闭。

Dereferencing a null pointer is Undefined Behaviour, and so whether you pass it as a reference or by value, the fact is that you've dereferenced it and therefore invoked UB, meaning from that point on all bets are off.

您已经在这里调用UB:

You've already invoked UB here:

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

这篇关于nullptr引用未定义的行为在C + +?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆