How to check whether or not C++ type is trivially copyable? I have a class, which uses memcpy and memcmp functions with specified template type T and I would like to fire assert for types, that are not safe to copy with memcpy. Is there any way to do that (with existing standard)?
A trivially copyable class is a class (defined with class, struct or union) that: uses the implicitly defined copy and move constructors, copy and move assignments, and destructor. has no virtual members. its base class and non-static data members (if any) are themselves also trivially copyable types.
However, it is important to realise that pointers are trivially copyable types, too. Whenever there are pointer inside the data structures you will be copying, you have to brainually make sure that copying them around is proper.
The following types are collectively called trivially copyable types: scalar types. trivially copyable class types. arrays of such types.
The diagnostic is not required, but std::atomic requires a trivially copyable type and std::string is not one.
No, not possible in C++98/C++03. Things like this are why <type_traits>
was added to C++0x. Some of the features from <type_traits>
can be implemented in C++03, often using the SFINAE principle, but several, including std::is_trivially_copyable<T>
, will simply require built-in compiler support.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With