加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – `x? 1:0`变成了40,未定义的行为?

发布时间:2020-12-16 10:10:02 所属栏目:百科 来源:网络整理
导读:我写了这段代码: #include cstdio#include queueclass Obj { bool x;public: Obj(): x(true) {} Obj(Obj o) { o.x = false; } ~Obj() { if(x) { std::puts("Here"); std::printf("%dn",x ? 1 : 0); } }};int main() { std::queueObj q; q.push(Obj()); q.p
我写了这段代码:

#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("%dn",x ? 1 : 0);
        }
    }
};

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

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

Here
40

通过以不同方式执行程序,数量可以是160,24,96或104.在Ideone没有打印任何东西.

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

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

解决方法

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

#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("%dn",x ? 1 : 0);
        }
    }
};

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

以上工作如预期(打印“此处1”).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读