首先需要明確的是,這篇文章不是要描述unique_ptr和shared_ptr兩個只能指針之間的區別,主要就是為了用unique_ptr對shared_ptr進行初始化。
#include
#include
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
myUnique(customArrayAllocator(4), customArrayDeleter);
std::cout << "unique_ptr constructed\n";
std::shared_ptr
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