C++ Logo


Advanced search

Subject: Anonymous unions with non-trivial member types
From: Yongwei Wu (wuyongwei_at_[hidden])
Date: 2020-08-28 06:35:26

Since C++11, unions may have non-trivial member types, as long as custom
non-static special member functions are provided by the user to remedy the
deleted special functions. So far, I have not found clear evidence from the
Standard whether anonymous unions may have non-trivial member types. The
following code may be compiled by GCC 8+ and MSVC, but is rejected by Clang
10 (interestingly, Clang 7 accepts it):

#include <iostream> // std::cout/endl
#include <string> // std::string

using namespace std;

struct StringIntChar {
    enum { String, Int, Char } type;
        if (type == String) {
    union {
        string string_value;
        int int_value;
        char char_value;

int main()
    StringIntChar obj{.type = StringIntChar::String,
                      .string_value = "Hello world"s};
    cout << obj.string_value << endl;

I am aware I am using some C++20 features here. The key question is only
about anonymous unions. Can they have non-trivial member types, as in the
code? Is the compilation problem a regression bug in Clang?

Thanks in advance.

Best regards,


Yongwei Wu
URL: http://wyw.dcweb.cn/

STD-DISCUSSION list run by std-discussion-owner@lists.isocpp.org

Older Archives on Google Groups