smart pointer

Download Smart pointer

Post on 02-Jul-2015

1.085 views

Category:

Education

10 download

Embed Size (px)

DESCRIPTION

之前分享的智能指针

TRANSCRIPT

  • 1.

2. Agenda

3.

  • ->*
  • Owenership

4. ->* template 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(new Foo); foo->get(); (*foo).get(); 5. :Bad Code

  • int main(int argc, char** argv) {
  • string* my_name = new string("wuliang");
  • cout his_children = son; son->his_parent = father; 13. weak_ptr
    • class Children {
    • public:
    • boost::weak_ptr his_parent;
    • };

    14.

    • Storage Policy
    • Ownership policy
    • Conversion policy
    • Checking policy

    15. Storage Policy

    16. 17. 18. 19. 20. 21. Conversion policy

    • void Fun(Something* p);
    • ...
    • SmartPtr sp(new Something);
    • Fun(something);

    22.

    • template
    • class SmartPtr {
    • public:
    • operator T* () {return pointee_};
    • };

    23. Checking policy

    • NULL
    • * -> NULL

    24. #include #include #include #include using namespace std; typedef Loki::SmartPtr SmartPointer; int main(int argc, char **argv) { SmartPointer myName(new string("Wu Liang")); SmartPointer copiedName = myName; cout