c++ - 了解 unique_ptr get() 函数

标签 c++ smart-pointers unique-ptr

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

我的理解有误吗?

最佳答案

Will the unique_ptr get() stops the object from getting destroyed through some reference counting?

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

完美的缺陷:

{
    auto a = std::make_unqiue<int>(0);
    delete a.get();
} // double free

隐藏事实:

int* getMemory(int N) {
    auto Up = std::make_unique<int[]>(N);
    return Up.get();
} // The unique_ptr goes out of scope and frees the allocated memory

int* foo = getMemory(1);
*foo = 10; // undefined behavior - the memory is free'd

关于c++ - 了解 unique_ptr get() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76020345/

相关文章:

c++ - 隐藏的对话框暂时占据焦点

c++ - 四元数旋转不起作用

c++ - 将 vector 成员变量返回给外部类的最佳方法

c++ - pthread_cond_t 和 std::condition_variable 的区别

c++ - 将 .lib 文件添加到 Visual Studio 2015 中的项目

c++ - 从 shared_ptr 到 weak_ptr 多态性的转换

c++ - 使用 unique_ptr 制作的堆元素是否移动到堆栈上仍然分配在堆上?

c++ - unique_ptr 和默认可构造指针

c++ - SegFault 删除 QTreeWidgetItem

c++ - 通过引用线程函数传递 unique_ptr 的托管对象