unique_ptr 指定删除器和 shared_ptr 指定删除器是有区别的,unique_ptr 指定删除器的时候需要确定删除器的类型,所以不能像 shared_ptr 那样直接指定删除器,举例说明:
代码如下:
#include <iostream>
#include <memory>
#include <string>
using namespace std;class Test
{
public:Test(){cout << "construct" << endl;}Test(int x) :m_num(x){cout << "construct x = " << x << endl;}Test(string str){cout << "construct str = " << str << endl;}~Test(){cout << "destruct" << endl;}void setValue(int v){m_num = v;}void print(){cout << "m_num = " << m_num << endl;}private:int m_num;
};int main()
{using ptrFunc = void(*)(Test *);unique_ptr<Test,ptrFunc> ptr4(new Test("hello"), [](Test * t){cout << "------------------" << endl;delete t;});return 0;}
测试结果:
代码如下:
//error 捕获了外部变量的lambda表达式只能看做仿函数using ptrFunc = void(*)(Test *);unique_ptr<Test, ptrFunc> ptr4(new Test("hello"), [=](Test * t){cout << "------------------" << endl;delete t;});
上面的代码中错误原因是这样的,在 lambda 表达式没有捕获任何外部变量时,可以直接转换为函数指针,一旦捕获了就无法转换了,如果想要让编译器成功通过编译,那么需要使用可调用对象包装器来处理声明的函数指针:
#include <iostream>
#include <memory>
#include <string>
#include <functional>
using namespace std;class Test
{
public:Test(){cout << "construct" << endl;}Test(int x) :m_num(x){cout << "construct x = " << x << endl;}Test(string str){cout << "construct str = " << str << endl;}~Test(){cout << "destruct" << endl;}void setValue(int v){m_num = v;}void print(){cout << "m_num = " << m_num << endl;}private:int m_num;
};int main()
{//error 捕获了外部变量的lambda表达式只能看做仿函数/*using ptrFunc = void(*)(Test *);unique_ptr<Test, ptrFunc> ptr4(new Test("hello"), [=](Test * t){cout << "------------------" << endl;delete t;});*///捕获了外部变量的lambda表达式只能看做仿函数,要把它包装才可以unique_ptr<Test,function<void(Test*)>> ptr4(new Test("hello"), [=](Test * t){cout << "------------------" << endl;delete t;});return 0;}
独占的智能指针可以管理数组类型的地址,能够自动释放。
代码如下:
int main()
{//独占的智能指针可以管理数组类型的地址,能够自动释放unique_ptr<Test[]> ptr4(new Test[3]);return 0;
}
测试结果: