C++ 代码的行为取决于编译器 [英] behavior of c++ code changes depending on the compiler

查看:63
本文介绍了C++ 代码的行为取决于编译器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 c 和 c++ 真的很陌生

I’m really new to c and c++

我尝试使用结构来创建一个类似列表的结构,基本上可以包含浮点数和列表.

I tried to experiment with structs to create a list-like structure that can contain float and lists, basically.

这段代码可以编译,但它的行为因编译器而异:

This code compiles, but it behaves differently depending on the compiler:

  • 使用最新版本的visual studio社区,它输出5,然后输出0.

使用 online shell,我得到 5 然后5

with an online shell, I get 5 and then 5

当向量通过函数时,我想要得到的第二个.

The one I would want to get is the second one when the vector gets passed through the function.

代码如下:

#include <iostream>
#include <vector>

using namespace std;

struct Box {
    Box(char t) {
        type = t;
    }
    union Value {
        float number;
        vector<Box>* elements;
    };
    Value value;
    char type;
};

Box newBox() {
    Box aBox('l');

    vector<Box> newVec;
    newVec.assign(5, Box('n'));


    aBox.value.elements = &newVec;
    cout << aBox.value.elements->size() << "\n";
    return aBox;

}

int main()
{
    Box test = newBox();
    cout << test.value.elements->size();  // this is not always working nicely
}


这是从哪里来的?

我的代码有问题吗?

有没有更好的方法来创建这种结构?

And is there a better way to create this kind of structure?

推荐答案

在这一行:

aBox.value.elements = &newVec;

您正在存储局部变量的地址.当您从 newBox 函数返回时,该变量会消失,然后通过指针访问该内存会调用未定义的行为.

you are storing the address of a local variable. When you return from the newBox function, that variables dies, and then accessing that memory via the pointer invokes undefined behavior.

这篇关于C++ 代码的行为取决于编译器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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