Smart Pointer
Deal with c++11’s smart pointer facility.
brief
Smart pointers are class objects that behave like built-in pointers but also manage objects that you create with new so that you don’t have to worry about when and whether to delete them - the smart pointers automatically delete the
managed object for you at the appropriate time.
- shared_ptr
- weak_ptr
- unique_ptr
shared_ptr (共享指针)
- referenced-counted smart pointer
- Shared Ownership with shared_ptr
引用计数智能指针:可以和其他 boost::shared_ptr 类型的智能指针共享所有权。 在这种情况下,当引用对象的最后一个智能指针销毁后或者被重新赋值或者使用了reset(),对象才会被释放。多个shared_ptr对象可以拥有同一个对象。
在继承中的例子:
shared_ptr<Thing> base_ptr(new Thing(2));
shared_ptr<Food> derived_ptr;
///if static_cast<Derived* >(base_ptr.get()) is valid, then the following is valid:
base_ptr->showID();
///cast failed
derived_ptr = static_pointer_cast<Food>(base_ptr);
shared_ptr<Food> a(new Food);
// a->showID();
derived_ptr->showID();
使用 make_shared 更加高效
There are actually two dynamic memory allocations that happen: one for the object itself from the new, and then a second for the manager object created by the shared_ptr constructor. Since memory allocations are slow, this means that creating a shared_ptr is slow relative to using either a raw pointer, or a so-called “intrusive” reference- counted smart pointer where the reference count is a member variable of the object. To address this problem, C++11 includes a fun