Loving std::unique_ptr

I am falling in love with std::unique_ptr.

It’s part of the new C++11 standard and is pretty much a smarter way of doing auto_ptr. The main difference is that you can not assign or copy it. Meaning it really is just a handle for a pointer that deletes it’s content when it gets destroyed.

Which doesn’t sound like much, but it will stop you from making so many mistakes. The benefit of it is that now you have a clear concept of who owns the content of the pointer.

Any time where you used to do

class Foo
{
    Base * member;
public:
    Foo() : member(new Derived()) {}
    ~Foo() { delete member; }
};

should just be replaced with

class Foo
{
    std::unique_ptr<Base> member;
public:
    Foo() : member(new Derived()) {}
};

Read the rest of this entry »