Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

c++ - When is a type in c++11 allowed to be memcpyed?

My question is the following:

If I want to copy a class type, memcpy can do it very fast. This is allowed in some situations.

We have some type traits:

  • is_standard_layout.
  • is_trivially_copyable.

What I would like to know is the exact requirements when a type will be "bitwise copyable".

My conclusion is that a type is bitwise copyable if both of is_trivally_copyable and is_standard_layout traits are true:

  1. It is exactly what I need to bitwise copy?
  2. Is it overconstrained?
  3. Is it underconstrained?

P.S.: of course, the result of memcpy must be correct. I know I could memcpy in any situation but incorrectly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can copy an object of type T using memcpy when is_trivially_copyable<T>::value is true. There is no particular need for the type to be a standard layout type. The definition of 'trivially copyable' is essentially that it's safe to do this.

An example of a class that is safe to copy with memcpy but which is not standard layout:

struct T {
  int i;
private:
  int j;
};

Because this class uses different access control for different non-static data members it is not standard layout, but it is still trivially copyable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...