This is a great answer about smart pointers, such as unique pointers: What is a smart pointer and when should I use one?.
Here is an example they provide as the simplest use of a unique pointer:
void f()
{
{
std::unique_ptr<MyObject> ptr(new MyObject(my_constructor_param));
ptr->DoSomethingUseful();
} // ptr goes out of scope --
// the MyObject is automatically destroyed.
// ptr->Oops(); // Compile error: "ptr" not defined
// since it is no longer in scope.
}
However, this begs the question: in cases such as this, where the goal is to simply delete the object (free the memory) the unique pointer points to when it goes out of scope, why not just put the whole object on the stack instead, like this??
void f()
{
{
MyObject myobj(my_constructor_param);
myobj.DoSomethingUseful();
} // myobj goes out of scope --
// and is automatically destroyed.
// myobj.Oops(); // Compile error: "myobj" not defined
// since it is no longer in scope.
}
It seems to me the only logic can be that some objects are so stinking large they may overflow the stack, as stacks seem to be limited to a few dozen KB to a few MB (C/C++ maximum stack size of program), whereas a heap can be hundreds of GB!
What's the logic? Give me some insight here into this seemingly unnecessary use case of the unique pointer. What am I missing?
Related:
- "Another feature of the stack to keep in mind, is that there is a limit (varies with OS) on the size of variables that can be stored on the stack. This is not the case for variables allocated on the heap." (https://gribblelab.org/CBootCamp/7_Memory_Stack_vs_Heap.html)