Lesson 61. Smart pointer class templates

1. smart pointer template

STL (header file memory smart pointer template): auto_ptr
A at the end of the life cycle, pointing to the destruction of memory space.
B can not point to heap array, can only point to heap objects (variables).
C a heap space belongs to only one smart pointer. Object
d. a plurality of smart pointers point to the same object can not be a heap space (when more than a bunch of smart pointers point to the same space, auto_ptr before the pointer will be set to empty, finally leaving only the last smart pointer to this space)

eg:

#include <iostream>
#include <string>
#include <memory>

using namespace std;

class Test
{
    string m_name;
public:
    Test(const char* name)
    {
        cout << "Hello, " << name << ". " << endl;
        
        m_name = name;
    }
    
    void print()
    {
        cout << "I'm " << m_name << ". " << endl;
    }
    
    ~Test()
    {
        cout << "Goodbye, " << m_name << ". " << endl;
    }
};

int main()
{
    auto_ptr<Test> pt(new Test("D.T.Software"));        // 智能指针类创建一个Test类型的指针pt
    
    cout << "pt = " << pt.get() << endl;        // 得到pt指针的地址

    pt->print();
    
    cout << endl;
    
    auto_ptr<Test> pt1(pt);     // 用pt来初始化pt1这个智能指针,理论上来说这里               
                                // 应该是两个指针指向同一段内存空间,但事实上不是那样的
    cout << "pt  = " << pt.get() << endl;
    cout << "pt1 = " << pt1.get() << endl;
    
    return 0;
}

Other smart pointer classes in STL

share_ptr

 With reference counting mechanism to support a plurality of objects pointers point to the same memory space

weak_ptr

 Share_ptr introduced with a smart pointer class

unique_ptr

 A pointer to a memory object points, can not copy constructor and assignment (i.e., when a plurality of pointers to the same memory space when only the first valid)

Guess you like

Origin www.cnblogs.com/huangdengtao/p/12017612.html