Do I need a destructor if I allocate memory in a local environment?

Say I have a function:

1
2
3
4
void createNode()
{
   Node *someNode = new Node; 
}


When the function terminates, does that local Node variable memory become automatically de-allocated because it is local or does it stay in the heap until I use a destructor?
The object continues to exist until you delete it:
 
delete someNode;

If the Node only needs to live for the duration of the function, it's probably better to use automatic storage:
1
2
3
void createNode(){
    Node someNode;
}

Or, if for whatever reason to need dynamic allocation, use a smart pointer:
1
2
3
void createNode(){
    auto someNode = std::make_unique<Node>();
}

Whenever possible, avoid using naked pointers. It's all too easy to forget to delete one or to delete one more than once. Let the compiler take care of resource management whenever possible.
Okay. So it would be better to use dynamic allocation if you want the node to exist after the function terminates, correct?
Topic archived. No new replies allowed.