Why isn't memcpy guaranteed to be safe for non-POD types?

前端 未结 5 1304
再見小時候
再見小時候 2020-12-03 22:09

I read about this paragraph from a few questions posted on SO.

I can\'t quite figure out why memcpy isn\'t guaranteed to be safe for a non-POD type.

5条回答
  •  情书的邮戳
    2020-12-03 22:46

    C++11 note: The quote in the question is a rather old version of the rule. Since C++11, the requirement is trivially copyable which is much weaker than POD.


    memcpy can be used from any object. You get a bitwise image of the object.

    If the object is not POD, then the image cannot be used as if it were the same type as the original object, because the lifetime rules require initialization to complete first.

    In such cases, the image is merely a bunch of bytes. That might still be useful, for example to detect changes in the internal representation of an object over time, but only operations valid on bytes (such as comparison between two images) are legal, and not operations that require an object of the original type.

提交回复
热议问题