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

后端 未结 6 2165
误落风尘
误落风尘 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:49

    No, doing so can cause a lot of problems. You should always copy C++ types by using the assignment operator or copy constructor.

    Using a bitwise copy breaks any kind of resource management because at the end of the day you are left with 2 objects for which 1 constructor has run and 2 destructors will run.

    Consider as an example a ref counted pointer.

    void foo() {
      RefPointer p1(new int());
      RefPointer p2;
      memcpy(&p2,p1,sizeof(RefPointer));
    }
    

    Now both p1 and p2 are holding onto the same data yet the internal ref counting mechanism has not been notified. Both destructors will run thinking they are the sole owner of the data potentially causing the value to be destructed twice.

提交回复
热议问题