学习unique_ptr的用法

Last Updated: 2023-12-29 03:11:35 Friday

-- TOC --

unique_ptr管理了一个独占的资源,当unique_ptr对象销毁的时候,其所管理的资源也会一并销毁。使用unique_ptr并配合make_unique,可以让代码完全不出现new和delete,即所谓的naked new and delete。

下面是一段测试代码:

#include <iostream>
#include <vector>
#include <memory>
using namespace std;
using vint = vector<int>;


int main(){
    {
        unique_ptr<vint> x { new vint };
        x->push_back(1);
        x->push_back(2);
        cout << (*x)[0] << " " << *((*x).begin()+1) << endl;  // 1 2
    }
    {
        unique_ptr<vint[]> x { new vint[2] };
        x[0].push_back(1);
        x[0].push_back(2);
        x[1].push_back(3);
        x[1].push_back(4);
        cout << x[0][0] << " " << *(x[1].begin()+1) << endl;  // 1 4

    }
    {
        unique_ptr<vint> x;
        try{
            x = make_unique<vint>();
        }catch(const bad_alloc&){
            cout << "make_unique failed..\n";
        }
        x->push_back(1);
        x->push_back(2);
        cout << (*x)[0] << " " << *((*x).begin()+1) << endl;  // 1 2
    }
    {
        unique_ptr<vint[]> x;
        try{
            x = make_unique<vint[]>(2);
        }catch(const bad_alloc&){
            cout << "make_unique failed..\n";
        }
        x[0].push_back(1);
        x[0].push_back(2);
        x[1].push_back(3);
        x[1].push_back(4);
        cout << x[0][0] << " " << *(x[1].begin()+1) << endl;  // 1 4
    }
    {
        unique_ptr<vint> x { make_unique<vint>() };
        (*x).push_back(1);
        (*x).push_back(2);
        unique_ptr<vint> y { move(x) };
        cout << (*y)[0] << " " << *((*y).begin()+1) << endl;  // 1 2
    }

    return 0;
}

unique_ptr与RAII这个C++中不断重复的概念密切相关,下面一段文字来自《A Tour of C++》:

Let each resource have an owner in some scope and by default be released at the end of its owners scope. In C++, this is known as RAII (Resource Acquisition Is Initialization) and is integrated with error handling in the form of exceptions. Resources can be moved from scope to scope using move semantics or “smart pointers,” and shared ownership can be represented by “shared pointers”.

本文链接:https://cs.pynote.net/sf/c/cpp/202312288/

-- EOF --

-- MORE --