一个人怎么能将简单成员与memcpy结合起来?

Ale*_* G. 10 c++ std standards-compliance unions language-lawyer

我不太了解标准报价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;
}
Run Code Online (Sandbox Code Playgroud)

因此,一个问题导致另一个问题:

  • 上面的代码安全吗?还是UB排名第二/第一,memcpy取决于union所接触的成员用户?招募memcpy两个成员都太过分了吗?

  • 如果不安全,那么我如何在没有一些活动联合成员标志的情况下实现复制构造函数?

Obl*_*ica 5

您使用两个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 has only function_p as active and the second memcopy triggers undefined behavior.