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.

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. Jun 8, 2015 at 14:50
  • Good question, but the information you need is duplicated elsewhere.
    – OMGtechy
    Jun 8, 2015 at 14:53
  • possible duplicate of How to return smart pointers (shared_ptr), by reference or by value?
    – OMGtechy
    Jun 8, 2015 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 8, 2015 at 15:00

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.