Copy constructor with pointers

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

    More often than not, if YOU need to write a copy constructor or assignment operator you're doing something wrong. Leave the copy constructors and assignment operators to the implementers of the standard library. Compose your classes of already-copyable and assignable elements and you won't have to write your own.

    For example, maybe that int * member should be a std::vector instead.

    If you can't make the class default copyable/assignable, maybe you can make it non-copyable/assignable by declaring, but not implementing, a private copy constructor and assignment operator.

    Only if none of the above are feasible should you implement your own copy constructor or assignment operator.

提交回复
热议问题