Thomas
Thomas

Reputation: 6196

Attempting to reference a deleted function error with anonymous union

struct Dingus {
union {
    int dingly[4 *4];
    vec3 dinglyDo;
}diddly;
inline Dingus() {}
};

This code produces the error

error C2280: 'Dingus::<unnamed-type-diddly>::<unnamed-type-diddly>(void)': attempting to reference a deleted function

Oddly, when I delete the "diddly" which was giving a reference to the union, there is no error.

The vec3 is a struct from the GLM library, I can replace the type with some other classes and i'll get the same error... but if I replace it with something simple like float I don't get the error

Since removing the "diddly" removes the error, this seems to be a different question than this one

Upvotes: 0

Views: 2097

Answers (2)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33924

As of c++17 you can use std::variant instead of a union to solve this problem. Your code could easily be replaced by:

struct Dingus {
    std::variant<std::array<int, 4*4>, vec3> diddly;
    inline Dingus() {}
};

Upvotes: 0

Jonathan Wakely
Jonathan Wakely

Reputation: 171393

You've declared a member of that anonymous union type, and so the member needs to be initialized in the Dingus constructor. Because the union has a member of non-trivial type it has no default constructor, so it can't be initialized in the Dingus constructor.

You can define a constructor for the union type which says what should happen when it's default-constructed e.g.

struct Dingus {
  union U {
    int dingly[4 *4];
    vec3 dinglyDo;
    U() : dingly() { }
  } diddly;
  inline Dingus() {}
};

Upvotes: 3

Related Questions