C++ 程序员应该知道哪些常见的未定义行为? [英] What are all the common undefined behaviours that a C++ programmer should know about?

查看:33
本文介绍了C++ 程序员应该知道哪些常见的未定义行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C++ 程序员应该知道哪些常见的未定义行为?

What are all the common undefined behaviours that a C++ programmer should know about?

说,比如:

a[i] = i++;

推荐答案

指针

  • 取消引用NULL 指针
  • 取消引用由new"返回的指针大小为零的分配
  • 使用指向生命周期结束的对象的指针(例如,堆栈分配的对象或删除的对象)
  • 取消引用尚未明确初始化的指针
  • 执行指针运算,产生超出数组边界(上方或下方)的结果.
  • 在数组末尾以外的位置取消引用指针.
  • 转换指向不兼容类型对象的指针
  • 使用memcpy复制重叠缓冲区.
    • 以负偏移量或超出该对象的大小(堆栈/堆溢出)读取或写入对象或数组
    • 有符号整数溢出
    • 评估一个没有数学定义的表达式
    • 将值左移负值(负值右移是实现定义的)
    • 将值移位大于或等于数字中的位数(例如 int64_t i = 1; i <<= 72 未定义)
    • 将数值转换为目标类型无法表示的值(直接或通过 static_cast)
    • 在明确赋值之前使用自动变量(例如,int i; i++; cout << i;)
    • 在接收信号时使用除 volatilesig_atomic_t 以外的任何类型的对象的值
    • 尝试在其生命周期内修改字符串文字或任何其他常量对象
    • 在预处理期间将窄字符串与宽字符串文字连接
    • Casting a numeric value into a value that can't be represented by the target type (either directly or via static_cast)
    • Using an automatic variable before it has been definitely assigned (e.g., int i; i++; cout << i;)
    • Using the value of any object of type other than volatile or sig_atomic_t at the receipt of a signal
    • Attempting to modify a string literal or any other const object during its lifetime
    • Concatenating a narrow with a wide string literal during preprocessing
    • 不从返回值的函数返回值(直接或通过从 try 块流出)
    • 同一实体的多个不同定义(类、模板、枚举、内联函数、静态成员函数等)
    • 模板实例化中的无限递归
    • 使用不同的参数调用函数或链接到函数定义为使用的参数和链接.
    • 具有静态存储持续时间的对象级联销毁
    • 分配给部分重叠对象的结果
    • 在静态对象的初始化过程中递归地重新进入一个函数
    • 从对象的构造函数或析构函数中对对象的纯虚函数进行虚函数调用
    • 引用对象的非静态成员,还没有被构造或已经被破坏
    • 不以换行符结尾或以反斜杠结尾的非空源文件(C++11 之前)
    • 反斜杠后跟一个不属于字符或字符串常量中指定转义码的字符(这是在 C++11 中实现定义的).
    • 超出实现限制(嵌套块的数量、程序中的函数数量、可用的堆栈空间......)
    • 不能用 long int
    • 表示的预处理器数值
    • 类似函数的宏定义左侧的预处理指令
    • #if 表达式中动态生成定义的标记
    • A non-empty source file that doesn't end with a newline, or ends with a backslash (prior to C++11)
    • A backslash followed by a character that is not part of the specified escape codes in a character or string constant (this is implementation-defined in C++11).
    • Exceeding implementation limits (number of nested blocks, number of functions in a program, available stack space ...)
    • Preprocessor numeric values that can't be represented by a long int
    • Preprocessing directive on the left side of a function-like macro definition
    • Dynamically generating the defined token in a #if expression
    • 在销毁具有静态存储持续时间的程序期间调用 exit

    这篇关于C++ 程序员应该知道哪些常见的未定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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