3 ms·
Using your example let's assume myBar and myBaz are _owned_ by Foo. Before C++11 you would typically do this: class Foo { public: Foo() : myBar(0),
by yannickt 14y ago
Using your example let's assume myBar and myBaz are _owned_ by Foo. Before C++11 you would typically do this:
class Foo {
public:
Foo() : myBar(0), myBaz(0)
{
myBar = new Bar;
myBaz = new Baz;
}
~Foo
{
if (myBar) delete myBar;
if (myBaz) delete myBaz;
}
private:
Bar *myBar;
Baz *myBaz;
};
In C++11, the above could be written like this:
class Foo {
public:
Foo() : myBar(new Bar), myBaz(new Baz)
{
}
private:
std::unique_ptr<Bar> myBar;
std::unique_ptr<Baz> myBaz;
};
You don't need to call delete because the unique_ptr destructor will do it for you.
You would only need to use shared_ptr when ownership is shared among multiple objects. A shared_ptr holds a reference counter that is incremented every time it is copied, and decremented every time it is destroyed or re-assigned. When the reference counter reaches zero, the pointer is automatically deleted.
- tyree732 14y agoAnd once they get around to adding std::make_unique (or you add it to your codebase yourself), you won't even need new there either.
- SamReidHughes 14y agoPre C++11 you would use a scoped_ptr in that scenario. And for the record, the conditionals in that destructor are redundant, deleting a null pointer does nothing.