给shared_ptr添加自定义删除器的几种方式
1. 使用lambda表达式
1 #include <iostream> 2 #include <memory> 3 4 int main() 5 { 6 std::shared_ptr<int>(new int[5](), [](int *x) { 7 std::cout << "Delete function called" << std::endl; 8 delete[] x; 9 }); 10 }
2. 使用普通函数
1 #include <iostream> 2 #include <memory> 3 4 void deleter(int *x) 5 { 6 std::cout << "Delete function called" << std::endl; 7 delete[] x; 8 } 9 10 int main() 11 { 12 std::shared_ptr<int>(new int[5](), deleter); 13 }
3.使用类重载:
1 #include <iostream> 2 #include <memory> 3 4 class Deleter 5 { 6 public: 7 void operator()(int *x) 8 { 9 std::cout << "Delete function called" << std::endl; 10 delete[] x; 11 } 12 }; 13 14 int main() 15 { 16 std::shared_ptr<int>(new int[5](), Deleter()); 17 }
4. 使用std::default_delete:
1 #include <memory> 2 #include <vector> 3 #include <algorithm> 4 5 int main() 6 { 7 { 8 std::shared_ptr<int> shared_good(new int[10], std::default_delete<int[]>()); 9 } 10 11 std::vector<int *> v; 12 for (int n = 0; n < 100; ++n) 13 v.push_back(new int(n)); 14 std::for_each(v.begin(), v.end(), std::default_delete<int>()); 15 }