了解 unique_ptr get() 函数

问题描述 投票:0回答:1

unique_ptr get() 会阻止对象通过一些引用计数被销毁吗?

考虑以下程序:

#include <memory>
#include <iostream>
int* getMemory(int N) {
    auto Up = std::make_unique<int[]>(N);
    return Up.get();
}


int main() {
    int* array = getMemory(10);
    for (int i=0;i<10;++i) {
        array[i] = i;
    }

    for(int i =0; i< 10; ++i) {
        std::cout<<array[i]<<"\n";
    }
}

我原以为这个程序会崩溃,因为 getMemory() 函数中的 unique_ptr 在调用后应该被销毁,所以 int* 的底层内存应该被取消分配。但令人惊讶的是它正在工作: https://godbolt.org/z/Gq1W7Gha8

我理解错了吗?

c++ smart-pointers unique-ptr
1个回答
0
投票

unique_ptr get() 会阻止对象通过一些引用计数被销毁吗?

不,一点也不。

std::unqiue_ptr
是一个拥有指针的简单包装器。没有分享。它拥有它。调用
get()
使调用者可以访问指针指向的内容 - 但所有权仍由
unique_ptr
持有。

完美瑕疵:

{
    auto a = std::make_unqiue<int>(0);
    delete a.get();
} // double free
© www.soinside.com 2019 - 2024. All rights reserved.