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/