Is it possible to return an entire linked list object from a method in C++ without running the destructor?
Basically I’m designing a C++ class where one of the class functions has it return another object of that same class (return myClass;). This class uses dynamic memory management (linked lists) in order to function properly.
When C++ returns the class, it’s really only returning the head reference, then, when it runs the destructor after the class function exits, it deletes all the nodes to which the head is linked.
Is there any way to really do this right?
Observing members:
0
Composing members:
0
4 Answers
Response moderated
Your description in the problem doesn’t really describe what you want it to do that you would call right, nor does it explain how it uses its linked list. If you haven’t figured out exactly what you want it to do in a consistent way that you can express, then no, you can’t do it right, because there’s nothing right to do. Once you do have a model of what you want to do that you can describe clearly, then yes, there will be a right way to do it.
You could look it up in a book.
Assuming I guess rightly about what you had in mind:
If a class has a linked list as a member, and a member function to create another instance of that class and return a pointer to that new object, then that member function should not be coded to delete the nodes of the new object, nor release its memory. The object should be designed to do that to its own linked list nodes when it gets destroyed, but not to the memory of objects it created.
~MyClass()
{
DeleteMyHeapMemory();
}
Answer this question 
This question is in the General Section. Responses must be helpful and on-topic.