函数指针类型别名与智能指针
Posted jz_cnblogs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了函数指针类型别名与智能指针相关的知识,希望对你有一定的参考价值。
1 // run in windows: std::system("pause") 2 #include <cstdlib> 3 #include <iostream> 4 #include <memory> 5 #include <functional> 6 7 using namespace std; 8 using namespace std::placeholders; 9 10 template <typename T> 11 using DeleteFunc = void(T*); 12 13 class Deleter; 14 15 template <typename T> 16 using DeleteMemberFunc = void(__thiscall Deleter::*)(T*)const; 17 18 // normal version 19 template <typename T> 20 inline void Delete(T* ptr) 21 { 22 cout << "[delete] address: " << ptr << ", value: " << *ptr << endl; 23 delete ptr; 24 } 25 26 // caller operator & static member function 27 class Deleter 28 { 29 public: 30 Deleter() = default; 31 ~Deleter() = default; 32 Deleter(const Deleter&) = default; 33 Deleter(Deleter&&) = default; 34 Deleter& operator=(const Deleter&) = default; 35 36 template <typename T> 37 void operator()(T* ptr) const { Delete(ptr); } 38 39 template <typename T> 40 static void StaticDelete(T* ptr) { ::Delete(ptr); } 41 } deleter; 42 43 // std::function 44 function<DeleteFunc<int>> funcobj = &Delete<int>; 45 function<DeleteFunc<int>> static_funcobj = &Deleter::StaticDelete<int>; 46 function<DeleteFunc<int>> member_funcobj = bind(&Deleter::operator()<int> , &deleter, _1); 47 48 // lambda 49 auto lambda_delete = [](int* ptr) { Delete(ptr); }; 50 51 using IntSPtr = shared_ptr<int>; 52 template <typename Func> using IntUPtr = unique_ptr<int, Func>; 53 54 int main(int argc, char* argv[]) 55 { 56 { 57 DeleteMemberFunc<int> member_func = &Deleter::operator(); 58 59 IntSPtr s1 = make_shared<int>(10); 60 IntSPtr s2(new int(11), &Delete<int>); 61 IntSPtr s3(new int(12), Deleter()); 62 IntSPtr s4(new int(13), &Deleter::StaticDelete<int>); 63 IntSPtr s5(new int(14), funcobj); 64 IntSPtr s6(new int(15), static_funcobj); 65 IntSPtr s7(new int(16), member_funcobj); 66 IntSPtr s8(new int(17), lambda_delete); 67 int* sp9 = new int(18); 68 (deleter.*member_func)(sp9); 69 70 unique_ptr<int> u1 = make_unique<int>(20); 71 IntUPtr<DeleteFunc<int>*> u2(new int(21), &Delete<int>); 72 IntUPtr<Deleter> u3(new int(22), Deleter()); 73 IntUPtr<DeleteFunc<int>*> u4(new int(23), &Deleter::StaticDelete<int>); 74 IntUPtr<decltype(funcobj)> u5(new int(24), funcobj); 75 IntUPtr<decltype(static_funcobj)> u6(new int(25), static_funcobj); 76 IntUPtr<decltype(member_funcobj)> u7(new int(26), member_funcobj); 77 IntUPtr<decltype(lambda_delete)> u8(new int(27), lambda_delete); 78 int* up9 = new int(28); 79 (deleter.*member_func)(up9); 80 } 81 82 std::system("pause"); 83 return 0; 84 }
以上是关于函数指针类型别名与智能指针的主要内容,如果未能解决你的问题,请参考以下文章