Copying structs with uninitialized members

后端 未结 4 1775
迷失自我
迷失自我 2020-12-30 20:47

Is it valid to copy a struct some of whose members are not initialized?

I suspect it is undefined behavior, but if so, it makes leaving any uninitialized members in

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-30 21:17

    In general, copying uninitialized data is undefined behavior because that data may be in a trapping state. Quoting this page:

    If an object representation does not represent any value of the object type, it is known as trap representation. Accessing a trap representation in any way other than reading it through an lvalue expression of character type is undefined behavior.

    Signalling NaNs are possible for floating point types, and on some platforms integers may have trap representations.

    However, for trivially copyable types it is possible to use memcpy to copy the raw representation of the object. Doing so is safe since the value of the object is not interpreted, and instead the raw byte sequence of the object representation is copied.

提交回复
热议问题