More Related Content
Similar to Smart pointer (20)
Smart pointer
- 4. 提供 -> 和 * template <typename T> class SmartPtr { public: explicit SmartPtr(T* pointee) {this->pointee_ = pointee;}; ~SmartPtr(); SmartPtr& operator =(const SmartPtr& other); T& operator *() const {return *pointee_;}; T* operator ->() const {return pointee_;}; private: T* pointee_; }; class Foo { public: void get(); }; SmartPtr<Foo> foo(new Foo); foo->get(); (*foo).get();
- 11. 它们之间的区别 std::auto_ptr 销毁式、不能应用于 STL 容器和数组 scoped_ptr const std::auto_ptr scoped_array const std::auto_ptr for array shared_ptr 引用计数实现多个指针共享对象的所有权 shared_array weak_ptr intrusive_ptr ?
- 12. 为什么需要 weak_ptr (强引用) class Children { public: boost::shared_ptr<Parent> his_parent; }; boost::shared_ptr<Parent> father(new Parent()); boost::shared_ptr<Children> son(new Children()); // memory leak will be happended in here father->his_children = son; son->his_parent = father;
- 24. 一切都组合起来 #include <cstdlib> #include <iostream> #include <string> #include <loki/SmartPtr.h> using namespace std; typedef Loki::SmartPtr<string, Loki::RefCounted, Loki::DisallowConversion, Loki::AssertCheck, Loki::DefaultSPStorage> SmartPointer; int main(int argc, char **argv) { SmartPointer myName(new string("Wu Liang")); SmartPointer copiedName = myName; cout << *myName << endl; cout << *copiedName << endl; }
Editor's Notes
- 当然,拥有权的管理其实有很多种方式,比如: Std::auto_ptr 的转移后销毁 Boost::shared_ptr 的引用计数 其实你完成可以设计一个智能指针,让它不主动地释放它们所指的对象,而是去做一些别的什么事
- 这里有
- 强引用就是被引用的对象活着的话,这个引用也存在。也就是说,当至少存在一个强引用时,那么这个对象就不会被释放,典型的就是 shared_ptr 相对强引用,弱引用只是一个观察者,它不会接受所有权,也不会增加计数器
- 当然,还有一些其他的细节: ( 1 )最好不要重载 address-of 操作符 ( 2 )相等性测试和不等性测试 ( 3 )比较 ( 4 )对 Arrary 的支持 ……
- 空间上的浪费
- 效率上的浪费