是nullptr引用在c++中的未定义行为
Are nullptr references undefined behaviour in C++?
下面的代码使用了nullptr
指针和引用:
#include <cstdio>
void printRefAddr(int &ref) {
printf("printAddr %pn", &ref);
}
int main() {
int *ip = nullptr;
int &ir = *ip;
// 1. get address of nullptr reference
printf("ip=%p &ir=%pn", ip, &ir);
// 2. dereference a nullptr pointer and pass it as reference
printRefAddr(*ip);
// 3. pass nullptr reference
printRefAddr(ir);
return 0;
}
问题:在c++标准中,有注释语句1..有效的代码或未定义的行为?
这与不同版本的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.
由于ir
只是*ip
的影子,因此它本身不会引起未定义行为。
未定义的行为是使用指向nullptr_t
的指针。我的意思是使用*ip
。因此
int &ir = *ip;
^^^
引起UB
相关文章:
- 编译C++时未定义的引用
- vscode g++链路故障:体系结构x86_64的未定义符号
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 不知道某个东西是否被忽略会引入未定义的行为吗
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 未定义的引用在哪里
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- c++11评估顺序(未定义的行为)
- 使用mysql c++连接器的未定义引用
- 从python调用openMP共享库时,未定义opnMP函数
- 在 Mac 上使用 CMAKE 将 FFTW 和 FFTWPP 链接到项目中时未定义的符号
- Cmake 链接问题:未定义对 Button::mousePressEvent(QGraphicsSceneMouseE
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 具有外部"c"和程序集的未定义函数
- 此增量后语句是否会导致未定义的行为?
- 尝试调用 .h 文件中定义的变量时出现变量未定义错误
- 在C++中使用内联方法时出现未定义的符号错误
- 对 Scalar ::Scalar() 的未定义引用