gpt4 book ai didi

c++ - 分配给已删除/未初始化的对象

转载 作者:行者123 更新时间:2023-11-28 01:29:56 25 4
gpt4 key购买 nike

我有这样一个类

struct foo {
bool type;
union {
struct { std::string s; };
struct { std::function<std::string(void)> f; };
};
};

我需要定义赋值运算符,但是当我分配不同的类型时,我基本上是在分配给未初始化的字段(我知道我必须先显式调用析构函数)。

我的猜测是这样的赋值是未定义的行为,因为我不知道字符串或函数的赋值是否不会重用某些字段。

如何在不调用任何未定义行为的情况下正确执行此操作?

我仅限于 C++11。

最佳答案

My guess is that such assignment is undefined behavior, since I don't know if assignment of string or function doesn't reuse some fields.

猜对了!赋值总是有一个前提条件,即左侧实际上是该类型的对象。如果我们在左侧没有物体,则所有赌注均无效。

How can I do this correctly without invoking any undefined behavior?

施工!当您没有对象时,获得对象的唯一方法就是创建它。因为我们想在特定位置创建它,所以这是新的位置。

我不确定你为什么要把你的类型包装在一个额外的结构中,你想这样做:

union U {
U() { }
~U() { }

std::string s;
std::function<std::string(void)> f;
} u;

这样,您的赋值运算符将是:

foo& operator=(foo const& rhs) {
if (type) {
if (rhs.type) {
u.s = rhs.u.s;
} else {
u.s.~string();
new (&u.f) std::function<std::string(void)>(rhs.u.f);
}
} else {
if (!rhs.type) {
u.f = rhs.u.f;
} else {
u.f.~function();
new (&u.s) std::string(rhs.u.s);
}
}

return *this;
}

您需要重构其中的一些以支持移动分配而无需大量重复,但这是粗略的想法。

关于c++ - 分配给已删除/未初始化的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51969900/

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