给 shared_ptr 添加自定义 deleter 的几种方式
1. 使用函数
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <memory>
void deleter(Sample* ptr) {
std::cout << "delete function called" << std::endl;
delete ptr;
}
std::shared_ptr<Sample> sp(new Sample, deleter);
2. 使用仿函数
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <memory>
struct Deleter {
void operator()(Sample* ptr) {
std::cout << "deleter function called" << std::endl;
delete ptr;
}
};
std::shared_ptr<Sample> sp(new Sample, Deleter{});
3. 使用 lambda 表达式
1
2
3
4
5
6
7
#include <iostream>
#include <memory>
std::shared_ptr<Sample> sp(new Sample, [](Sample* ptr) {
std::cout << "lambda function called" << std::endl;
delete ptr;
});
4. 使用 std::default_delete
1
2
3
4
#include <iostream>
#include <memory>
std::shared_ptr<Sample> sp(new Sample, std::default_delete<Sample>{});
本文由作者按照 CC BY 4.0 进行授权