Hacker News new | past | comments | ask | show | jobs | submit login

One thing i like about using std::unique_ptr now that we have and use std::move() is to annotate in the API when you want to own the heap object being passed or to say that the api consumer should own the reference.

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:

    class X {
     Y* y;
    };
Does X owns Y? or is owned by Z and X is just using it?

    class X {
     std::unique_ptr<Y> y;
    };
Now you know for sure X owns y.

    class X {
      std::unique_ptr<Y> CreateY();
      Y* CreateY();
    };
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:

    void AddY(std::unique_ptr<Y> y)
    void AddY(Y* y)
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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: