将 unsigned int 的最大值转换为 int 并期望结果为 -1 是否可移植?

Is it portable to cast the max value of a unsigned int into an int and exepect the result to be -1?

我找到了一个 C++ 代码,我们在其中将一个初始化为其最大值的 unsigned int 32 转换为一个 signed int,并期望它是 -1。 它在经过测试的编译器上运行良好,但它真的可以移植吗?

int GetBusinessDataID()
{
    u32_t id = ~0;

    // Some code that may return a valid ID.

    return id; // Here we expect to return -1.
}

自 C++20 以来,integral conversions 保证了这一点;在 C++20 之前,这是实现定义的。

If the destination type is signed, the value does not change if the source integer can be represented in the destination type. Otherwise the result is

  • implementation-defined (until C++20)

  • the unique value of the destination type equal to the source value modulo 2n where n is the number of bits used to represent the destination type. (since C++20).