I am writing a code for doubly linked list. Now for copy constructor which is a good way. Just copying pointers of head and tail or copying whole list to new list? Thank you.

有帮助吗?

解决方案

Copy the whole list.

I'd say one of main purposes of copy-constructor is copying the whole list and make two independent objects.

Copy/Move the whole list to a new list to avoid unintended dangling pointers due to destructing one of copies, unintended modifications and many other problems... After copy it should have two independent copies.


Also, since you have to write a copy-constructor, you should write:

  • Destructor
  • Copy assignment operator
  • Move constructor
  • Move assignment operator

Read Rule of five. Moreover, you can take advantages of copy-and-swap idiom.

其他提示

I think you can read more about moveconstructor or copy constructor in C++11. For a deep copy, you need to copy the element.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top