How to pass deleter to make_shared?

前端 未结 5 1010
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 13:39

Since C++11, because of several reasons, developers tend to use smart pointer classes for dynamic lifetime objects. And with those new smart pointer classes, standards, even

5条回答
  •  旧巷少年郎
    2020-12-13 13:59

    If you use a custom deleter you can't use make_unique or make_shared functions when you create a smart pointer objects . Since we need to provide our custom deleter these functions do not support that .

    Don't use make_unique or make_shared if you need a custom deleter or adopting a raw pointer from elsewhere.

    The idea is if you need a specialized way to delete your object you probably need a specialized way to create them too .

    Let say we a class Test

    #include     
    using namespace std;    
    class Test
    {
    private : 
        int data; 
        public : 
        Test() :data{0}
        {
            cout << "Test constructor (" << data << ")" << endl;
        }
        Test(int d) : data{ d }
        {
            cout << "Test constructor (" << data << ")" << endl; 
        }
        int get_data() const { return data; }
        ~Test()
        { 
            cout << "Test Destructor (" << data << ')' << endl; 
        }
    };
    
    // main function. 
    int main()
    {
       // It's fine if you use  make_shared and custom deleter like this
       std::shared_ptr ptr(new Test{1000},
                [](Test *ptr)
                {
                    cout << "some Code that you want to execute "; 
                    delete ptr;
                });
             return 0;
    }
    

    But if you use make_shared function you will get a compiler error

    std::shared_ptr ptr = make_shared(1000,
                [](Test *ptr){
                   cout << "some Code that you want to execute "; 
                   delete ptr;
                });
    

    Basically make_shared function is a wrapper for new and delete and if you want a custom deleter you have to provide you own new and delete

提交回复
热议问题