为什么我不能创建一个包含 vec3 对象的联合?

Why can't I make a union containing a vec3 object?

我似乎无法创建一个联合,其中成员是或包含 glm::vec3 对象(表示坐标的对象,在本例中包含 3 个浮点数)。 (source code for glm::vec)

在以下代码中使用:

struct Event {
    enum Type{
        tRaw,
        tAction,
        tCursor,
    } type;
    union {
        SDL_Event raw;
        struct {
            uint16 actionID;
            bool released;
        } action;
        struct {
            glm::vec3 prevPos;
            glm::vec3 pos;
        } cursor; // offending object, compiles if this is removed
    } data;
};

Visual Studio 给我以下智能感知错误。

"Error: the default constructor of "union Event::<unnamed>" cannot be referenced -- it is a deleted function"

如果删除,联合编译没有任何问题。是什么导致了这个问题,有什么办法可以解决吗?

一旦你的 union 中有一个非平凡的类型(因此,语言 强制 "correct" 初始化,即构造函数调用),你必须明确地写下你的constructors/destructors:

#include <SDL/SDL.h>
#include <glm/vec3.hpp>
#include <stdint.h>
#include <new>
#include <vector>

struct Event {
    enum Type{
        tRaw,
        tAction,
        tCursor,
    } type;
    struct Cursor {
        glm::vec3 prevPos;
        glm::vec3 pos;
    };
    union {
        SDL_Event raw;
        struct {
            uint16_t actionID;
            bool released;
        } action;
        Cursor cursor;
    };
    Event(const SDL_Event &raw) : type(tRaw) {
        new(&this->raw) SDL_Event(raw);
    }
    Event(uint16_t actionID, bool released) : type(tAction) {
        this->action.actionID = actionID;
        this->action.released = released;
    }
    Event(glm::vec3 prevPos, glm::vec3 pos) : type(tCursor) {
        new(&this->cursor) Cursor{prevPos, pos};
    }
    Event(const Event &rhs) : type(rhs.type) {
        switch(type) {
        case tRaw:      new(&this->raw) SDL_Event(raw); break;
        case tAction:   memcpy((void *)&action, (const void *)&rhs.action, sizeof(action)); break;
        case tCursor:   new(&this->cursor) Cursor(rhs.cursor);
        }
    }

    ~Event() {
        if(type == tCursor) {
            this->cursor.~Cursor();
        }
        // in all other cases, no destructor is needed
    }
};

int main() {
    // Construction
    Event ev(1, false);
    SDL_Event foo;
    Event ev2(foo);
    glm::vec3 pos;
    Event ev3(pos, pos);
    // Copy construction & destruction
    std::vector<Event> events;
    events.push_back(ev);
    events.push_back(ev2);
    events.push_back(ev3);
    events.clear();
    return 0;
}

一些注意事项:

  • 我避开了 data 成员,而是选择了匿名 union;这避免了很多样板,否则我必须在 union 中编写这些构造函数(因为它是 union 构造函数被删除并且必须明确定义),然后在外部添加转发器;它还大大简化了析构函数的编写(同样,它必须写在union内部,但是union不知道外部type;你可以解决这个问题,但它既乏味又冗长);
  • 我必须明确命名 Cursor 联合,否则在语法上不可能调用它的析构函数(除非使用模板技巧);
  • 我没有实现赋值运算符;这并不复杂,但老实说这很乏味。你可以找到一个基本的蓝图(检查是否相同type;如果相同,则进行常规分配;否则,销毁活动成员和placement-new到新的)in the link I posted before in the comments.

综上所述,这些东西已经在 C++17 中以更通用的方式实现,如 std::variant,因此,如果您有足够新的编译器,您可以考虑改用它。