简体   繁体   English

带有布尔指针的奇怪 C++ 输出

[英]Strange C++ output with boolean pointer

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

#include <iostream>
using namespace std;

int main() {
    int n = 2;
    string s = "AB";
    bool* xd = nullptr;
    for (int i = 0; i < n; i += 100) {
        if (xd == nullptr) {
            bool tmp = false;
            xd = &tmp;
        }
        cout << "wtf: " << " " << (*xd) << " " << endl;
    }
}

When I run this on my own mac with g++ -std=c++17, I get a random integer every time (which is odd since *xd should be a bool).当我使用 g++ -std=c++17 在我自己的 mac 上运行它时,我每次都会得到一个随机整数(这很奇怪,因为 *xd 应该是一个布尔值)。 Weirdly enough, this doesn't happen on online IDEs like csacademy and onlinegdb.奇怪的是,这不会发生在像 csacademy 和 onlinegdb 这样的在线 IDE 上。

if (xd == nullptr) { bool tmp = false; xd = &tmp; }

tmp is an automatic variable. tmp是一个自动变量。 It is destroyed automatically at the end of the scope where the variable is declared.它在声明变量的范围结束时自动销毁。 In this case, the lifetime of the object ends when the if-statement ends.在这种情况下,对象的生命周期在 if 语句结束时结束。 At that point , the pointer xd which pointed to the variable becomes invalid.此时,指向变量的指针xd变为无效。

 (*xd)

Here, you indirect through an invalid pointer.在这里,你通过一个无效的指针间接。 That's something that a program must never do.这是程序绝对不能做的事情。 The behaviour of the program is undefined.程序的行为是未定义的。 The program is broken.程序坏了。 Don't do this.不要这样做。

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

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