Vis*_*rma 1 c++ smart-pointers unique-ptr c++14
我注意到这可以编译:
#include<memory>
#include<iostream>
using namespace std;
int main()
{
unique_ptr<int>a(nullptr);
if(!a)
cout<<"NULLPTR";
}
Run Code Online (Sandbox Code Playgroud)
但是,这不是:
#include<memory>
#include<iostream>
using namespace std;
int main()
{
unique_ptr<int>a(NULL);
if(!a)
cout<<"NULL";
}
Run Code Online (Sandbox Code Playgroud)
我正在使用具有多个函数的库,这些函数返回原始指针,并且使用后必须手动释放它们。我想使用unique_ptr(带有自定义删除器)来管理这样的原始指针。我担心那些函数返回NULL的情况,因为我认为这可能会引起一些问题。
没关系。导致问题的原因只是NULL宏(扩展到0大多数编译器)。0与的nullptr_t和T*构造函数都匹配unique_ptr,因此它是模棱两可的并且不会编译。
当初始化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);
Run Code Online (Sandbox Code Playgroud)
注意:如果您不与用于malloc()分配的C函数接口,而与与一起使用的C ++函数接口new,则不要使用自定义删除器。的默认删除器unique_ptr已使用delete。
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |