Can I make a bitwise copy of a C++ object?

后端 未结 6 2163
误落风尘
误落风尘 2021-02-09 18:52

Can C++ objects be copied using bitwise copy? I mean using memcopy_s? Is there a scenario in which that can go wrong?

6条回答
  •  [愿得一人]
    2021-02-09 19:39

    If they're Plain Old Data (POD) types, then this should work. Any class that has instances of other classes inside it will potentially fail, since you're copying them without invoking their copy constructors. The most likely way it will fail is one of their destructors will free some memory, but you've duplicated pointers that point to it, so you then try to use it from one of your copied objects and get a segfault. In short, don't do it unless it's a POD and you're sure it will always be a POD.

提交回复
热议问题