When do we need to know if a class is trivial?

std::is_trival<T>::valuecan determine if the class T is trivial. However, I can’t come up with a script that needs this information.

Are there any examples?

Some of my thoughts:

If the class T is trivial, does this mean that T can be safely copied using memcpyas follows:

T t1, t2;
memcpy(&t1, &t2, sizeof(T));

?

+2
source share
2 answers

, , , memcpy. , std::atomic. T, atomic<T> ( ) T atomic<T> memcpy, , , , memcmp.

C- ++- , . .

+6

, /anything/, . , - : std::ostream::write std::istream::read.

template<typename T>
std::enable_if<std::is_trivial<T>, void> 
bin_write(std::ostream& out, const T& data) {
  out.write(reinterpret_cast<const char*>(&data), sizeof(T));
}

template<typename T>
std::enable_if<std::is_trivial<T>::value, T> 
bin_read(std::istream& in) {
  using T_in = std::remove_cv_t<T>; //even if T is const, the buffer can't be
  T_ buffer;
  in.read(reinterpret_cast<char*>(&buffer), sizeof(T_));
  return buffer;
}

, raw- ( , std::experimental::observer_ptr). , . , , , , CCC GCC GCC.

0

Source: https://habr.com/ru/post/1543720/


All Articles