How can I call a private destructor from shared_ptr?

I have a resource_manager class that supports std::vector<boost::shared_ptr<resource> > internally. resource_manager is the friend class of resource . I want the resource be created / deleted only by resource_manager , so I made its constructors private (which works fine).

However, if I make the destructor private, the code does not compile because the destructor is called boost::shared_ptr , which is not another resource . I’m thinking about enforcing the "do not delete by clients" rule, returning only const resource* from resource_manager , but for some reason I am not happy with the security provided by this method (what if the client somehow follows a pointer to non-constant?)

Besides the obvious solution not to use shared_ptr , do you have any solution / best solution to my problem?

+6
source share
2 answers

You can pass a custom selector to a common pointer. So just create a delete functor or a function (up to you), which in turn is a friend your class:

 class Secret { ~Secret() { } friend class SecretDeleter; friend void SecretDelFunc(Secret *); }; class SecretDeleter { public: void operator()(Secret * p) { delete p; } }; void SecretDelFunc(Secret * p) { delete p; } std::shared_ptr<Secret> sp1(new Secret, SecretDeleter()); std::shared_ptr<Secret> sp2(new Secret, SecretDelFunc); 
+11
source

Perhaps declare shared_ptr<resource> as a friend? shared_ptr does not call the constructor and should only destroy if your resource manager frees the pointer before all clients destroy their shared_ptrs. This will not allow clients to violate protection, but will allow clients to maintain the resource in active mode from resource_manager "will".

+1
source

Source: https://habr.com/ru/post/901949/


All Articles