mercredi 22 août 2018

Assignment to deleted/uninitialized object

I have a class like this

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

I need to have assignment operators defined, but when I'm assigning different type I'm basicly assigning to uninitialized field (I know I have to explicitly call destructor first).

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?

I am limited to C++11.

Aucun commentaire:

Enregistrer un commentaire