实战c++中的智能指针unique_ptr系列--通过unique_ptr对shared_ptr进行初始化

首先需要明确的是,这篇文章不是要描述unique_ptr和shared_ptr两个只能指针之间的区别,主要就是为了用unique_ptr对shared_ptr进行初始化。

#include <iostream>
#include <memory>

int main()
{
    std::cout << "start!\n";
    auto customArrayAllocator = [](unsigned int num){
        std::cout << "custom array allocator\n";
        return new int[num];
    };

    std::cout << "allocator constructed\n";

    auto customArrayDeleter = [](int *ptr){
        std::cout << "custom array deleter\n";
        delete[] ptr;
    };

    std::cout << "deleter constructed\n";

    std::unique_ptr<int[], decltype(customArrayDeleter)>
        myUnique(customArrayAllocator(4), customArrayDeleter);

    std::cout << "unique_ptr constructed\n";

    std::shared_ptr<int>
        myShared = std::move(myUnique);

    std::cout << "shared_ptr constructed\n";
}

输出为:
start!
allocator constructed
deleter constructed
custom array allocator
unique_ptr constructed
shared_ptr constructed
custom array deleter

从输出,通俗的讲,就是unique的构造和删除器都传递给了shared指针。

引用:
http://stackoverflow.com/questions/30495941/initialization-of-shared-ptrt-from-unique-ptrt?rq=1

你可能感兴趣的:(C++,unique-ptr)