C++11 智能指针unique_ptr,在析构函数中释放内存,支持自定义释放函数
常用语法
申请数组 std::unique_ptr<int[]> ptr(new int[N]);
申请对象 std::unique_ptr<A> ptr2(new A);
释放或重置 reset(..)
获取指针 get()
示例代码:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <memory>
#include <functional>
#include <cstdio>
using namespace std;
class A {
public:
A(int a, int b) { cout << "A(" << a << "," << b << ")" << this << endl; }
A() { cout << "A()" << this << endl; }
~A() { cout << "~A()" << this << endl; }
void print() {
cout << "print()" << endl;
}
};
int main() {
{
int N = 4;
std::unique_ptr<int[]> ptr(new int[N]);
//access like an array
for (int i = 0; i < N; i++) {
ptr[i] = i;
}
//access like an array
for (int i = 0; i < N; i++) {
cout << ptr[i];
}
cout << endl;
}
{
cout << "use reset\n";
std::unique_ptr<A> ptr2(new A);
A *b = new A;
ptr2.reset(b);
}
{
std::unique_ptr<A[]> ptr2(new A[4]);
ptr2.reset();
}
{
//auto close file
std::unique_ptr<std::FILE, int(*)(std::FILE *)> fp(std::fopen("demo.txt", "w"), std::fclose);
//std::unique_ptr<std::FILE, std::function<void(FILE *)>> fp(std::fopen("demo.txt", "w"), [](FILE * fp) {fclose(fp); });
fprintf(fp.get(), "%s", "hello");
}
{
std::unique_ptr<A, std::function<void(A *)>> p(new A, [](A * ptr) {
std::cout << "destroying from a custom deleter...\n";
delete ptr;
});
}
{
auto p = std::make_unique<A>(1, 2);
p->print();
auto ptr = make_unique<int[]>(4);//int [4] array
}
}