|
|
|
|
|
by 4bpp
2730 days ago
|
|
I've written some heap-heavy code and never used unique_ptr, but I don't remember ever causing a double deletion. What's a pattern which you figure makes one prone to doing that? (On that basis, I'm a little inclined to suspect that it may be more of an issue for programmers who came from a deeply memory-managed language like Java and therefore don't build mental models to keep track until when a given allocation is needed.) (I have of course produced my share of memory leaks - praise be to valgrind - but they were all in scenarios where unique_ptr would have been too restrictive (without a Rust-style complete reconsideration of the code's ownership structure).) |
|
I get that if you just use it for usual the owning class, it doesnt provide that much, but it annotates lifetime, and its pretty cool when you get used to it.
if you see this:
Does X owns Y? or is owned by Z and X is just using it? Now you know for sure X owns y. Look how in the first example you know that X wont retain a copy of Y, and the caller will be considered the owner of the heap..Now in the second example you are not sure if X retain and will handle the deletion of Y, and you should use Y, while in the first example its perfectly clear the api intention.
the same here:
in the first you are aware you are passing the ownership of Y, in the second you wont be sure if you still need to handle the deletion yourself.Before std::move() i get it, but after you can pass things by moving them, i dont get it why anyone would not like to use this.
For me this is basically the "lifetime annotation" feature, only that it is by convention, and not enforced by the compiler. Unlike others these are the reasons why i dont feel the urge to jump the Rust bandwagon, and prefer to use things like Swift when i need a more "chill" environment to work, as i didnt feel more productive in Rust than in C++, while with Swift it happened and it also has a pretty good story perfomance wise.
I prefer to mix C++/Swift as my perfect duo, than try to make it all fit in one language, as this always lead to frustation and a lot of headaches.