gpt4 book ai didi

c++ - 我如何为尚未初始化的 union 成员分配内存

转载 作者:搜寻专家 更新时间:2023-10-31 00:59:57 25 4
gpt4 key购买 nike

我有两个成员的 union 。

union myUnion {
std::wstring mem1;
int mem2;
myUnion(std::wstring in){
this->mem1 = in;
}
myUnion(int in){
this->mem2 = in;
}
myUnion(const myUnion& in){
if(this->mem2){
this->mem2 = in.mem2;
}else{
this->mem1 = in.mem1;
}
}
};
//and then I make a vector out of the union:
std::vector<myUnion> unions;
//but when I try to push_back:
unions.push_back(L"A");

它很快就会出现运行时错误: 0xC0000005:访问冲突写入位置 0xCCCCCCCC。当我尝试调试这个程序时,我意识到 mem1 还没有分配内存。我真的不知道为什么会这样,我想知道我该如何解决。

最佳答案

在 C++ 中,union 不是一种非常自然的数据类型,因为它并不真正适合整个 C++ 的构造函数和析构函数概念。当您在 C++ 中创建 union 时,它不会为其任何可能的类型调用构造函数,因为它们将全部写在彼此之上。

所以这个构造函数

myUnion(std::wstring in){
this->mem1 = in;
}

将崩溃,因为 this->mem1 作为字符串的生命周期尚未开始。你将不得不使用类似的东西,调用 std::string ctor using placement new at that address。稍后,如果您更改数据类型,则必须确保在开始写入 union 的不同字段之前也为 this->mem1 调用 dtor,否则您将得到内存泄漏或损坏。

到目前为止,在 C++ 中做您想做的事情的更简单方法是使用像 boost::variant 这样的变体类型,它将为您处理所有样板和所有细节. (如果您只使用没有 ctors 或 dtor 的普通类型, union 是可以的。)

typedef boost::variant<std::wstring, int> MyUnion;

std::vector<MyUnion> unions;

unions.push_back(L"A");

关于c++ - 我如何为尚未初始化的 union 成员分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32303645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com