首页 > 解决方案 > 为什么 g++-11 '-O2' 包含错误,而 '-O0' 没问题?

问题描述

#include <limits>
#include <cstdint>
#include <iostream>

template<typename T>
T f(T const a = std::numeric_limits<T>::min(),
    T const b = std::numeric_limits<T>::max())
{
    if (a >= b)
    {
        throw 1;
    }

    auto n = static_cast<std::uint64_t>(b - a + 1);
    if (0 == n)
    {
        n = 1;
    }

    return n;
}

int main()
{
    std::cout << f<int>() << std::endl;
}

g++-11 -std=c++20 -O20应该输出1!

clang++ 符合预期。如果我-O2改为-O0,g++-11 也可以。

参见:在线演示

为什么 g++在正常的情况下 -O2 包含错误 -O0

标签: c++gccg++c++20internal-compiler-error

解决方案


b - a + 1a当and bare的类型intais INT_MINand bis INT_MAXas 有符号溢出是未定义的行为时,显然是 UB 。

来自cppreference:

当有符号整数算术运算溢出(结果不适合结果类型)时,行为未定义

int64_t在计算已经执行之前,您不会转换为。


推荐阅读