Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top