我注意到这个编译:
#include<memory>
#include<iostream>
using namespace std;
int main()
{
unique_ptr<int>a(nullptr);
if(!a)
cout<<"NULLPTR";
}
但是,这不会:
#include<memory>
#include<iostream>
using namespace std;
int main()
{
unique_ptr<int>a(NULL);
if(!a)
cout<<"NULL";
}
我正在使用一个有 several functions which return a raw pointer 的图书馆并且那些必须在使用后手动释放。我想使用 unique_ptr(带有自定义删除器)来管理此类原始指针。 我担心那些函数返回 NULL 的情况,因为我认为这可能会导致一些问题。
最佳答案
没关系。只是 NULL
宏(在大多数编译器上扩展为 0
)导致了问题。 0
匹配 unique_ptr
的 nullptr_t
和 T*
构造函数,因此它有歧义,不会编译。
当用指针变量或函数的返回值初始化一个unique_ptr
时,nullptr
、NULL
或使用了 0
。它们都具有相同的效果:一个空指针:
这很好,例如
int* int_p1 = NULL;
int* int_p2 = (int*)malloc(sizeof(int));
unique_ptr<int, decltype(&free)> a1(int_p1, free);
unique_ptr<int, decltype(&free)> a2(int_p2, free);
注意:如果您不与使用 malloc()
进行分配的 C 函数交互,而是与使用 new
的 C++ 函数交互,请不要使用自定义删除器。 unique_ptr
的默认删除器已使用 delete
。
关于c++ - 如何安全地将 unique_ptr 与可以返回 NULL 的函数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56520134/