简体   繁体   中英

Deep copy of a class with overloading of assignment operator

I am trying to create a deep copy of a class by overloading the equals operator - however, it does not seem to be working. Any help appreciated!

This is the class I am trying to copy:

class CMap {

public: 

    int m_nWidth;
    int m_nHeight;
    char* m_pData;
    void setDimensions(int nWidth, int nHeight);
    void operator = (CMap* rhs);

};

this is my overloaded operator:

CMap& operator = (const CMap&rhs)
    {
        if (this == &rhs)
        return *this;
    memcpy(this -> m_pData, rhs.m_pData, sizeof(char)*rhs.m_nWidth*rhs.m_nHeight);
        return *this;

    }

and this is the function call in the main. myMap is an array of CMaps.

CMap tempMap;
        tempMap.setDimensions(myMap[0].m_nHeight, myMap[0].m_nWidth);
        tempMap.m_pData = myMap[0].m_pData;
  • First: that's not the equals operator, that's the assignment operator.
  • Second: The assignment operator should have a const & parameter, not a pointer, and returns a reference to the object, not anything.
  • Third: Except you do something which interferes with the semantics of copying, a assigment overload which does the copy is provided by the compiler automatically.

Respect the point three, you have done one thing which does not do "true" copying: Using a dynamic array through a pointer. The compiler will only copy the pointer, so you have to write your own operator= to copy the array by hand (What you are trying in the question).

The easiest solution is: Use a container like std::vector instead of manual memory management . It has implemented correctly copying and assigment, so yo do not have to write your own operator= in your class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM