News for hackers. Stuff that matters.
Re:The Myth of Smart Pointers by jchw on Friday December 01, 2023 @11:26AM (#38488538)
You can't copy a unique_ptr. You're making two distinct unique_ptrs that point to the same thing. You can avoid that by... Well, by not doing that. Thankfully, the obvious way to do that, by copying the unique_ptr, is not allowed, thus making it harder for it to happen on accident.

The difference between code with unique_ptr and code without is that you can statically analyze the unsafe usages of unique_ptr, whereas it's basically not possible to do so for raw memory allocations. In fact, it solves most of the problem to just use make_unique wherever possible; you might be able to blanket-ban the normal constructor in your codebase and only use it with an exception.

The unique_ptr itself upholds all of the invariants that it promises to, which makes it a useful safety primitive. It, however, exists in a very, very memory-unsafe language, so of course, it's completely possible to blow past that and do anything else around it. This is unfortunate, but literally unavoidable if you want to stick to C++. In the meantime, if you're going to use C++, consider trying to limit yourself to the safe and correct subset of unique_ptr usage. You won't need as many exceptions as you think. (A neat thing I learned somewhat recently is that you can upgrade a unique_ptr directly into a shared_ptr. This is helpful because while shared_ptr is ideally very seldom used, it does mean that at least you don't have to eat the cost of shared_ptr until the exact point that you know you need it.)

There are no comments on this comment yet.