C++基础 指针<三>C++智能指针

95 阅读1分钟

image.png

image.png

image.png

#include <string>
#include <iostream>
#include <memory>
using namespace std;


int main() {
    {
        //确定 auto_ptr失效范围
        auto_ptr<int> p1(new int(10));
        cout << *p1 << endl;
        auto_ptr<string> lans[5] = {
                auto_ptr<string>(new string("C")),
                auto_ptr<string>(new string("java")),
                auto_ptr<string>(new string("C++")),
                auto_ptr<string>(new string("python")),
        };
        auto_ptr<string> pC;
        pC = lans[2];
        cout << "there is\n";
        for (int i = 0; i < 2; i++) {
            cout << *lans[i] << endl;
        }
        cout << "there is " << *pC << endl;
    }
    return 0;
}

在auto_ptr的析构函数中delete操作

image.png

打印

10
there is
C
java

image.png

{
    auto w = std::make_unique<int>(10);
    cout << *(w.get()) << endl;
    //auto w3=w;  //编译错误 如果想要把w复制给w3,是不可以的
    //因为复制从语义上来说,两个对象将共享同一块内存。
    auto w2 = std::move(w);
    cout << ((w.get() != nullptr) ? (*w.get()) : -1) << endl;
    cout << ((w2.get() != nullptr) ? (*w2.get()) : -1) << endl;
}

打印

10
-1
10

image.png

image.png

image.png

{
    auto w = shared_ptr<int>(new int(10));
    {
        auto w2 = w;
        cout << ((w.get() != nullptr) ? (*w.get()) : -1) << endl;
        cout << ((w2.get() != nullptr) ? (*w2.get()) : -1) << endl;
        cout << (w.use_count()) << endl;//返回的时引用计数
        cout << (w2.use_count()) << endl;
    }
    cout << w.use_count() << endl;
}

代码打印

10
10
2
2
1

move语法

{
    auto w = std::make_shared<int>(20);
    cout << *(w.get()) << endl;
    auto w2 = std::move(w);
    cout << ((w.get() != nullptr) ? ( *w.get()) : -1) << endl;
    cout << ((w2.get() != nullptr) ? (*w2.get()) : -1) << endl;
    cout << (w.use_count()) << endl;//返回的时引用计数
    cout << (w2.use_count()) << endl;
}

打印

20
-1
20
0
1