A type with std::is_trivially_copyable == true
is the only C++ type that may be safely copied with std::memcpy
or serialized to/from binary files with std::ofstream::write()
/ std::ifstream::read()
.
Definition
A "trivially copyable type" is a type whose storage is contiguous (and thus its copy implies a trivial memory block copy, as if performed with memcpy
).
A "trivially copyable class" is a class (defined with class
, struct
or union
) that:
- uses the default 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 type"s.
Example
// is_trivially_copiable example
#include <iostream>
#include <type_traits>
#include <map>
#include <vector>
struct A { int i; };
struct B {
int i,j;
B (const B& x) : i(x.i), j(1) {}; // copy ctor
};
struct C {
char str[30];
};
int main() {
std::cout << std::boolalpha;
std::cout << "is_trivially_copyable:" << std::endl;
std::cout << "int: " << std::is_trivially_copyable<int>::value << std::endl;
std::cout << "A: " << std::is_trivially_copyable<A>::value << std::endl;
// not trivially copyable because of the user-defined copy constructor
std::cout << "B: " << std::is_trivially_copyable<B>::value << std::endl;
// char array is trivially copyable
std::cout << "C: " << std::is_trivially_copyable<C>::value << std::endl;
// cpp containers are not trivially copyable
std::cout << "map: " << std::is_trivially_copyable<std::map<int, int>>::value << std::endl;
std::cout << "vec: " << std::is_trivially_copyable<std::vector<int>>::value << std::endl;
return 0;
}
is_trivially_copyable:
int: true
A: true
B: false
C: true
map: false
vec: false
网友评论