`x ?1 : 0` 变成了 40,未定义的行为? [英] `x ? 1 : 0` became 40, undefined behavior?

查看:34
本文介绍了`x ?1 : 0` 变成了 40,未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这段代码:

#include <cstdio>
#include <queue>

class Obj {
    bool x;
public:
    Obj(): x(true) {}
    Obj(Obj&& o) {
        o.x = false;
    }
    ~Obj() {
        if(x) {
            std::puts("Here");
            std::printf("%d\n", x ? 1 : 0);
        }
    }
};

int main() {
    std::queue<Obj> q;
    q.push(Obj());
    q.pop();
}

启用优化后,我得到了一个令人困惑的结果:

With optimization enabled, I got a confusing result:

Here
40

通过不同的方式执行程序,数字可以是1602496104.在 Ideone 上没有打印任何内容.

And the number can be 160, 24, 96 or 104 by executing the program in different ways. On Ideone nothing is printed.

这一定是一个未定义的行为.但我无法弄清楚出了什么问题.你能指出我的错误吗?

It must have been an undefined behavior. But I can't figure out what's wrong. Can you point out my mistake?

注意:我的编译器是 GCC 4.8.1,我的操作系统是 Windows 7.

Note: My compiler is GCC 4.8.1, and my operating system is Windows 7.

推荐答案

您没有在移动构造函数中初始化 this->x.我很确定未初始化变量的条件是未定义的行为.

You don't initialize this->x in your move constructor. I'm pretty sure conditionals on uninitialized variables are undefined behaviour.

#include <cstdio>
#include <queue>

class Obj {
    bool x;
public:
    Obj(): x(true) {}
    Obj(Obj&& o) : x(true) { // Hi!
        o.x = false;
    }
    ~Obj() {
        if(x) {
            std::puts("Here");
            std::printf("%d\n", x ? 1 : 0);
        }
    }
};

int main() {
    std::queue<Obj> q;
    q.push(Obj());
    q.pop();
}

以上按预期工作(打印Here 1").

The above works as expected (prints "Here 1").

这篇关于`x ?1 : 0` 变成了 40,未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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