[C ++ 11] _ [primary] _ [Use Cases of unique_ptr]
Scenario
Std: unique_ptr is a new smart pointer provided by C ++ 11. It has the following features:
A non-thread-safe alternative to auto_ptr, because it does not provide copy Constructor and Copy Assignable, that is, pointers cannot be copied. only one smart pointer has ownership of the contained instance object, meaning that only one smart pointer calls the Destructor after its lifecycle ends. it defaults to two methods for destroying objects, one is delete and the other is delete [], which is an array-less delete [] than auto_ptr. it does not reference counting and thread-safe methods, so its performance is actually higher than shared_ptr, but it is not applicable to unordered multi-threaded environments.
It can be used in a single-threaded environment.
It also applies to custom deleter, that is, it can proxy C free, CloseHandle, and so on. Example
# Include
# Include
# Include
Struct Foo {Foo () {std: cout <"Foo: Foo \ n ";}~ Foo () {std: cout <"Foo ::~ Foo \ n ";} void bar () {std: cout <" Foo: bar \ n ";}}; void f (const Foo &) {std :: cout <"f (const Foo &) \ n";} struct D {void operator () (Foo * foo) {std: cout <"D operator () "<std: endl; delete foo ;}}; void TestAutoDestroy () {// 1. A common new object. std: cout <"TestDestroy .................... "<std: endl; {std: unique_ptr
P1 (new Foo);} // 2. Common new [] object. {std: unique_ptr
P2 (new Foo [4]);} // 3. Custom deleter. {std: unique_ptr
P3 (new Foo) ;}} void TestOwner () {std :: cout <"TestOwner .................... "<std: endl; // 1. new object. std: unique_ptr
P1 (new Foo); // p1 owns Foo if (p1) p1-> bar (); {std: unique_ptr
P2 (std: move (p1); // now p2 owns Foo f (* p2); p1 = std: move (p2 ); // ownership returns to p1 p2-> bar (); std: cout <"destroying p2... \ n ";}p1-> bar ();} void TestArrayOwner () {std :: cout <"TestArrayOwner .................... "<std: endl; // 1. new [] object. std: unique_ptr
P1 (new Foo [4]); // p1 owns Foo if (p1) p1 [0]. bar (); {std: unique_ptr
P2 (std: move (p1); // now p2 owns Foo f (p2 [0]); p1 = std: move (p2 ); // ownership returns to p1 p2 [0]. bar (); std: cout <"destroying p2... \ n ";} p1 [0]. bar () ;}int main () {TestAutoDestroy (); TestOwner (); TestArrayOwner ();}
Output:
TestDestroy....................Foo::FooFoo::~FooFoo::FooFoo::FooFoo::FooFoo::FooFoo::~FooFoo::~FooFoo::~FooFoo::~FooFoo::FooD operator()Foo::~FooTestOwner....................Foo::FooFoo::barf(const Foo&)Foo::bardestroying p2...Foo::barFoo::~FooTestArrayOwner....................Foo::FooFoo::FooFoo::FooFoo::FooFoo::barf(const Foo&)Foo::bardestroying p2...Foo::barFoo::~FooFoo::~FooFoo::~FooFoo::~Foo