Is this error constructor a bad idea?

So, I have the feeling that this is a bad idea:

class Foo
{
public:
  Foo(const Foo& from)
  {
     memcpy(this, &from, sizeof(Foo));

     m_someData = new int[m_dataLength];
     memcpy(m_someData, from.m_someData, m_dataLength * sizeof(int));
  }

  private:
    int* m_someData;
    int m_dataLength;

};

Question: why? If the parameters memcpyare of the same type (and size), with the same location, where is the bad?

One potential problem that I see is if there is a field stringor vector<>, but I'm not sure if this is a real problem.

+4
source share
2 answers

If it Foocan be inferred from, consider what happens when you have a class Barderived from Foo, and copy-construct a Foofrom this instance Bar.

- , sizeof(Foo) , ( vtable), .

, Bar Foo, : Foo. memcpy.

:

, , - string vector<>, , .

? , .


, . , , , :

class Foo
{
public:
  Foo(const Foo& from)
  {
     m_Data = from.m_Data;

     m_Data.m_someData = new int[m_Data.m_dataLength];
     memcpy(m_Data.m_someData, from.m_Data.m_someData, m_Data.m_dataLength * sizeof(int));
  }

  private:
    struct Data {
      int* m_someData;
      int m_dataLength;
      // more fields
    };
    Data m_Data;

};

, m_Data = from.m_Data; , memcpy, , .

+7

:

struct boom1 {
  boom1(const boom1& from) 
  // reason 1: not using an initialisation list means double-initialisation of members. inefficient.
  {
    // reason 2: undefined behaviour on all subsequent access to
    // this->_s or from._s after this line
    memcpy(this, &from, sizeof(from));

    // reason 3: what if someone derived from this class? didn't you just overwrite the RTTI info pointer??
  }

  // reason 4: c++ already generates a copy constructor that does the right thing automatically. why are you laying mines for other developers?

  std::string _s;
}

", - POD, "...

... - , .

, , . . . , . Google. , , ?

+2

Source: https://habr.com/ru/post/1612592/


All Articles