简体   繁体   English

投向布尔时得不到1

[英]Not getting 1 when casting to bool

I have the following code: 我有以下代码:

#include <iostream>

void f(void* buffer) {
    int x = static_cast<bool>(*(char*)buffer);
    int y = static_cast<bool>(*(bool*)buffer);
    std::cout << x << " " << y;
}

int main() {
    int a = 255;
    f(&a);
}

On GCC 9.1, I'm getting the following output: 在GCC 9.1上,我得到以下输出:

1 255 1255

Why the cast to bool with (char*) cast results x to be 1 and the cast to bool with (bool*) cast results y to be, in this case, 255? 在这种情况下,为什么用(char*) boolbool结果x为1,而使用(bool*) bool(bool*)结果y为255?

Why the cast to bool ... with (bool*) cast results ...? 为什么用(bool *)强制转换为bool ...?

Because the behaviour of the program is undefined. 因为程序的行为是不确定的。

Standard says (quoting the latest draft): 标准说(引用最新草案):

[basic.lval] [basic.lval]

If a program attempts to access the stored value of an object through a glvalue whose type is not similar ([conv.qual]) to one of the following types the behavior is undefined : 如果程序尝试通过其类型与以下类型之一不相似([conv.qual])的glvalue访问对象的存储值, 则行为未定义

  • the dynamic type of the object, 对象的动态类型,
  • a type that is the signed or unsigned type corresponding to the dynamic type of the object, or 类型是与对象的动态类型相对应的有符号或无符号类型,或者
  • a char, unsigned char, or std::byte type. 字符,无符号字符或std :: byte类型。

bool is not similar to dynamic type of buffer , it is neither unsigned nor unsigned corresponding type, nor is it char unsigned char , or std::byte . bool与动态类型的buffer ,它既不是unsigned也不是unsigned对应类型,也不是char unsigned charstd::byte Therefore behaviour is undefined. 因此,行为是不确定的。

Why the cast to bool with (char*) cast results x to be 1 为什么用(char *)强制转换为布尔值会导致x为1

Because the first byte of a contained a value that did not represent a zero. 因为第一个字节a包含一些并不代表零值。 Whether this will be the case depends on the CPU architecture. 是否会这样取决于CPU体系结构。 The order of bytes of an integer is implementation defined. 整数的字节顺序由实现定义。

Note that the behaviour would be well defined in this case, because char is listed as one of the exceptions in the quoted rule. 请注意,在这种情况下,行为将得到很好的定义,因为char被列为引用规则中的例外之一。

You need to use reinterpret_cast<int *> . 您需要使用reinterpret_cast<int *> For example 例如

int y = static_cast<bool>(*reinterpret_cast<int*>( buffer ));

Here is a demonstrative program 这是一个示范节目

#include <iostream>

int main()
{
    int x = 255;
    void *buffer = &x;
    int y = static_cast<bool>(*reinterpret_cast<int*>( buffer ));

    std::cout << y << '\n';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM