Hacker News new | ask | show | jobs
by SideQuark 23 days ago
If it's on the stack, it's almost free to do.

If it's held by a unique_ptr, then it auto frees, but there is a lot of programmer work to ensure things behave well, and there are nuances to allocating something into the unique_ptr.

If it's a std::shared_ptr, which is the closest to what people think of, it's then a reference counted object, which requires a little more storage, and also has the ability to be mishandled as a pointer, screwing it up, or making the wrong type of copy of the shared_ptr, so two there are two things, and also fails to release object in the case of circluar references.

Then there's a lot of other subtle things you can do, and none of this is as lightweight as a pointer, and none is as automatic as what most people think of as garbage collection.

And each has costs and tradeoffs, which is why C++ added them: making certain tradeoffs easier to use, but it requires solid understanding of how such things work.