Is there a way to change the delete action to an existing instance of shared_ptr

I have a function in which I want the cleanup action to be performed in 90% of cases, but in 10% I want some other action to be performed.

Is it possible to use some standard control with a scope, for example, shared_ptr<> , so that initially it can have one delete action, and then in the function you can change the delete action?

 shared_ptr<T> ptr( new T, std::mem_fun_ref(&T::deleteMe) ); ptr.pn.d = std::mem_fun_ref(&T::queueMe); 
+7
c ++
source share
3 answers

I do not think you can change deleter after creating shared_ptr .

But why do you have to do this? Usually, when you create an object, you immediately know how to destroy it. This is unlikely to change.

If you really have to follow some specific procedures, you can still provide a custom debiter that does special things depending on the required logic.

+2
source share

There is a good reason why you need to change the debiter. Take this for example:

 int foo( std::shared_ptr<double>& bar ) { ... std::shared_ptr<double> p( my_allocator<double>::allocate(), my_deleter<double>() ); bar.swap(p); // this copies the deleter ... } int main( int, char** ) { std::shared_ptr<double> d; foo( d ); // d now has a new deleter that will be called when it goes out of scope ... } 

In this case, the foo () function allocates double * using some special allocator. It is also necessary to free this memory. The caller does not need to know how to free memory.

+2
source share

This makes no sense, as there is any number of shared_ptr that controls the ownership of the value. You will need to change them all, and this is not possible. Do not forget that the control unit is a part of the implementation, so the transition "aha, but changing it in the control unit" will not work.

Delete actions should be controlled by an instance owned by shared_ptr , for example.

 class C { ... void (C::action*)() { &C::action1 }; void action1(); void action2(); ~C() { (this->*action)(); } }; void test() { std::shared_ptr<C> a; a->action = &C::action2; // action2 gets invoked once `a` falls out of scope } 
0
source share

All Articles