Creating a copy constructor for a linked list

前端 未结 5 1679
Happy的楠姐
Happy的楠姐 2020-12-09 09:03

This is homework

I\'m working on implementing a linked list class for my C++ class, and the copy constructor has be very confusing for me.

T

5条回答
  •  渐次进展
    2020-12-09 09:38

    So here is my answer (don't know if that fits to your homework or not - instructors tend to have their own ideas sometimes ;):

    Generally a copy constructor should "copy" your object. I.e. say you have linkedList l1, and do a linkedList l2 = l1 (which calls linkedList::linkedList(l1)), then l1 and l2 are totally separate objects in the sense that modification of l1 doesn't affect l2 and vice versa.

    When you just assign pointers you won't get a real copy, as dereferencing and modifying either of them would affect both objects.

    You rather want to make a real deep copy of every element in your source list (or do a copy-on-demand only, if you want to be fancy).

提交回复
热议问题