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.
Asked
Active
Viewed 637 times
2 Answers
1
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.
-
oh.. dangling pointer .. right.. that must be main disadvantage in just copying pointers .. thank you so much.. I will copy whole list to new list .. @M M. – Rohit Sep 22 '13 at 17:47
-
C++11 has the "rule of five". (A move constructor and move assignment operator should be implemented as well.) – cHao Sep 22 '13 at 18:14
0
I think you can read more about move
constructor or copy
constructor in C++11. For a deep copy, you need to copy the element.

CS Pei
- 10,869
- 1
- 27
- 46
-
1This answer introduces two tools of C++ but it doesn't address the question. – masoud Sep 22 '13 at 17:41