2

In C++ I want to define a function which performs the deep copy of a list. The function is like:

ListNode *copyList(ListNode *head) {
  // the deep copy of the list 
}

The declaration of the function is fixed, I can't change it. I have to new as many list nodes as the original ones, but I can't force the user to remember delete them, which leads me to the use of smart pointers.

However, the return type is the raw pointer, the smart pointers defined within the function scope will expire at the end of the function, or at least to my limited understanding.

Please help me with this scenario which seems awkward and subtle. Thank you.

Alex
  • 75
  • 4
  • There is no way out of it. Other than providing an alternate function which does return by smart pointer. Than you just have to make it easier to use this terrible terror. – StoryTeller - Unslander Monica Jun 08 '15 at 14:50
  • Good question, but the information you need is duplicated elsewhere. – OMGtechy Jun 08 '15 at 14:53
  • possible duplicate of [How to return smart pointers (shared\_ptr), by reference or by value?](http://stackoverflow.com/questions/10643563/how-to-return-smart-pointers-shared-ptr-by-reference-or-by-value) – OMGtechy Jun 08 '15 at 14:53
  • 1
    You shouldn't worry about the user deleting all the nodes, you should provide a function that clears the list which the user can call, or do it the C++ way with a suitable destructor. – molbdnilo Jun 08 '15 at 15:00

0 Answers0