美文网首页
Understand std::is_trivially_cop

Understand std::is_trivially_cop

作者: 找不到工作 | 来源:发表于2021-12-23 12:16 被阅读0次

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

Referrence

  1. std::is_trivially_copyable - cppreference.com
  1. C++ named requirements: TriviallyCopyable - cppreference.com

  2. Copy constructors: trivial copy constructor - cppreference.com

  3. is_trivially_copyable - C++ Reference (cplusplus.com)

相关文章

网友评论

      本文标题:Understand std::is_trivially_cop

      本文链接:https://www.haomeiwen.com/subject/qhshqrtx.html