Date: Fri, 28 Aug 2020 19:35:26 +0800
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;
~StringIntChar()
{
if (type == String) {
string_value.~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
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;
~StringIntChar()
{
if (type == String) {
string_value.~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
-- Yongwei Wu URL: http://wyw.dcweb.cn/
Received on 2020-08-28 06:39:09