I have two dummy questions which have confused me for a while. I did do some searching online and read through much c++ tutorials, however I cannot find concrete answers.
Say we have a class named Node which is a building block of a singly linked list.
class Node
{
int data;
Node* next;
}
Fact1: local variables(non static) will be destroyed upon the exit of the corresponding functions.
Question1: How about the situations blow:
Node* func()
{
Node n;
Node* ptr=&n;
return n;
}
Will the node n be destroyed? Or we have to use the new operator to create the node and return a pointer to a heap memory. If both ways work, which one is a better approach?
Question2: How to write a destructor for the node class? (I find some similar questions on stackOverflow, but those answers focused on the destructor for the linked list. I already got that part. What I want is exactly a destructor for a Node class).
---------------------------------------EDIT------------------------------------
Thank all who gave me suggestions or pointed out my errors. I think I got my answers. Below is a note taken by me from your answers and that really knock out my confusions.
- It is not a good practice to return a stack memory address from a function since it will lead to undefined behaviors.
- Returning a heap memory is OK but we have to take care of the destruction of the objects.
- An alternative will be returning an object, benefiting from the copy constructor.