Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ is_trivially_copyable check

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)?

like image 530
axe Avatar asked Feb 14 '11 16:02

axe


People also ask

What does trivially copyable mean C++?

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.

Are pointers trivially copyable?

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.

Is array trivially copyable?

The following types are collectively called trivially copyable types: scalar types. trivially copyable class types. arrays of such types.

Is STD string trivially copyable?

The diagnostic is not required, but std::atomic requires a trivially copyable type and std::string is not one.


Video Answer


1 Answers

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.

like image 129
aschepler Avatar answered Sep 29 '22 23:09

aschepler