Copy constructor with pointers

前端 未结 9 1112
清歌不尽
清歌不尽 2020-12-14 10:08

I have recently discovered that when I have pointers within a class, I need to specify a Copy constructor.

To learn that, I have made the following simple code. It c

9条回答
  •  粉色の甜心
    2020-12-14 10:33

    When writing a Copy Constructor, you should allocate memory for all members. In your case:

    TRY::TRY(TRY const & copyTRY){
        pointer = new int(*(copyTry.pointer));
    }
    

    Operator= is somehow similar, but with no memory allocation.

    TRY& operator=(TRY const& otherTRY){
          this->a  = *(otherTry.pointer)
          return *this
    }
    

提交回复
热议问题