Search code examples
c++smart-pointers

C++: how does C++ know to destruct smart pointers inside containers?


In The C++ Programming Language, there is the following example (section 3.2.4).

unique_ptr<Shape> read_shape(istream& is);

void user()
{
    vector<unique_ptr<Shape>> v;
    while (cin)
        v.push_back(read_shape(cin));
    draw_all(v);
    // call draw() for each element
    rotate_all(v,45);
    // call rotate(45) for each element
} // all Shapes implicitly destroyed

Stroustrup is trying to make the point that by using unique_ptrs, one doesn't have to manually loop through the vector and delete all Shapes. I'm having trouble understanding why this is true.

The way I understand smart pointers is that if a smart pointer sptr is allocated on the stack, with something like

std::unique_ptr<Shape> sptr(new Shape());

you don't need to call delete on it at the end of the function. However, from what I can tell in the above example those smart pointers are not on the stack, they're put inside the data array of v, which is on the heap.


Solution

  • Whether the unique_ptr is on the stack or the heap doesn't really matter. What matters is that it will automatically call delete on the target pointer when its destructor runs.

    When the vector goes out of scope, the vector's destructor runs. That destroys all contained elements (calling their destructors in the process) and then deallocates its heap buffer.