gpt4 book ai didi

c++ - 一份拷贝如何使用 memcpy union 简单成员?

转载 作者:可可西里 更新时间:2023-11-01 17:57:21 25 4
gpt4 key购买 nike

我不太确定关于 memcpyunion 普通成员的标准引用。

考虑代码:

struct Test{
union
{
void(*function_p)(void*);
void(*function_p_c)(const void*);
};
Test(const Test &other)
{
using std::memcpy;
memcpy(&function_p, &other.function_p, sizeof(function_p)); //?
memcpy(&function_p_c, &other.function_p_c, sizeof(function_p_c)); //??
}
};

int main(void)
{
Test t1; t1.function_p = NULL; //let it be NULL for c++98 sake
Test t2(t1); // is it safe? does this set new active member of union?

return 0;
}

所以一个问题会引出另一个问题:

  • 上面的代码安全吗?或者它是第二个/第一个 memcpy 的 UB,具体取决于哪个 union 成员用户接触过?为两个成员调用 memcpy 是不是太过分了?

  • 如果它不安全,那么我如何在没有一些 flag-of-active-union-member 的情况下实现复制构造函数?

最佳答案

你用两个 memcpy 做的是未定义的行为。

The union is only as big as necessary to hold its largest data member. The other data members are allocated in the same bytes as part of that largest member. The details of that allocation are implementation-defined, and it's undefined behavior to read from the member of the union that wasn't most recently written. Many compilers implement, as a non-standard language extension, the ability to read inactive members of a union.

other 只有 function_p 处于事件状态,第二个 memcopy 触发未定义的行为。

关于c++ - 一份拷贝如何使用 memcpy union 简单成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57653718/

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