In the following, the my_char
class is said to not be trivial. I'm thinking that maybe the compiler is wrong, but maybe you know better than me what is wrong.
In file included from /usr/include/c /11/bits/basic_string.h:48,
from /usr/include/c /11/string:55,
from /usr/include/c /11/bits/locale_classes.h:40,
from /usr/include/c /11/bits/ios_base.h:41,
from /usr/include/c /11/ios:42,
from /usr/include/c /11/ostream:38,
from /usr/include/c /11/iostream:39,
from /home/alexis/my_char.cpp:2:
/usr/include/c /11/string_view: In instantiation ofclass std::basic_string_view<main()::my_char, std::char_traits<main()::my_char> >
:
/home/alexis/my_char.cpp:24:20: required from here
/usr/include/c /11/string_view:101:21: error: static assertion failed101 | static_assert(is_trivial_v<_CharT> && is_standard_layout_v<_CharT>); | ^~~~~~~~~~~~~~~~~~~~
/usr/include/c /11/string_view:101:21: note:
std::is_trivial_v<main()::my_char>
evaluates to false
Here is the compilable code my_char.cpp
:
#include <iostream>
struct my_char
{
typedef std::basic_string<my_char> string_t;
bool is_null() const
{
return f_char == CHAR_NULL;
}
static my_char::string_t to_character_string(std::string const & s)
{
my_char::string_t result;
for(auto const & ch : s)
{
my_char c;
c.f_char = ch;
result = c;
}
return result;
}
char32_t f_char = CHAR_NULL;
std::uint32_t f_line = 0;
std::uint32_t f_column = 0;
};
int main()
{
constexpr char32_t CHAR_NULL = '\0';
my_char::string_t str;
my_char c{ 'c' };
str = c;
std::cerr << "char = [" << static_cast<char>(str[0].f_char) << "]\n";
return 0;
}
g version: g (Ubuntu 11.2.0-7ubuntu2) 11.2.0
Command line used to compile the above:
g -Wall my_char.cpp
When I remove the to_character_string()
static function, it works. If I define that function outside of the class, it doesn't help. Still not trivial.
On the other hand, the is_null()
function causes no issue.
Why would that one function make the class non-trivial?
Note that this class works under Ubuntu 18.04. The non-trivial issue appeared on Ubuntu 21.10. I suppose that's either a new check or the old check just let it go.
For those interested by the complete class, it can be found here.
CodePudding user response:
Your class my_char
is not suitable as a character type for basic_string
. From cpp-reference:
The class template basic_string stores and manipulates sequences of char-like objects, which are non-array objects of trivial standard-layout type.
and if you follow the definition of trivial, we have among other requirements of a trivial default constructor:
T has no non-static members with default initializers. (since C 11)
If you remove the default initializers from the class members, your class should be good.
The reason that earlier compilers did not complain is that they did not have the conformity check.