ram*_*mbi 0 c++ struct pointers
我对 c 和 c++ 真的很陌生
我试着用结构来创建一个类似列表的结构,基本上可以包含浮点数和列表。
此代码可编译,但其行为因编译器而异:
使用最新版本的visual studio社区,它输出5然后0.
使用在线外壳,我得到5然后5
当向量通过函数时,我想要得到的第二个。
这是代码:
#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
}
Run Code Online (Sandbox Code Playgroud)
这是从哪里来的?
我的代码有问题吗?
有没有更好的方法来创建这种结构?
在这一行:
aBox.value.elements = &newVec;
Run Code Online (Sandbox Code Playgroud)
您正在存储局部变量的地址。当您从newBox函数返回时,该变量会消失,然后通过指针访问该内存会调用未定义的行为。