Copy constructor with pointers

前端 未结 9 1127
清歌不尽
清歌不尽 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:29

    if it has a pointer to a regular type then

    A::A(const A& a):
      pointer_( new int( *a.pointer_ ) )
    {
    }
    

    if it has a pointer to some base class then

    A::A(const &a ):
      pointer_( a.pointer_->clone() )
    {
    }
    

    Clone is a implementation of a prototype pattern

    Don't forget to delete the pointer in the destructor

    A::~A()
    {
        delete pointer_;
    }
    

    To fix your example

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

提交回复
热议问题