Is there a smart boost pointer class that can be configured to be deleted upon destruction?

I have a list of smart pointers. I want some of these smart pointers to act like regular pointers, that is, they simply refer to the instance and are not involved in freeing it. For example, they may point to instances allocated on the stack. Other smart pointers in the list should act like regular boost :: shared_ptr.

This is what the class looks like:

template<class T> smart_ptr { private: T *p; boost::shared_ptr<T> sp; public: smart_ptr(T *p): p(p), shared(0) { } // p will not be deleted smart_ptr(boost::shared_ptr<T> &sp): p(sp.get()), sp(sp) { } T *get() const { return p; } } 

If there is a boost class that does this, I would rather use it instead of writing a class. It seems they are not, or am I mistaken?

+4
source share
4 answers

One constructor for shared_ptr accepts a destructor method, and you can pass an empty functor.

Using Custom Deallocator in boost :: shared_ptr

(You only need an empty function.)

+13
source

I have this little class in my toolbar for this:

 struct nodelete { template <typename T> void operator()( T * ) {} }; 

Using:

 int main() { SomeClass sc; boost::shared_ptr<SomeClass> p( &sc, nodelete() ); // ... } 
+3
source

It sounds like boost :: weak_ptr: http://www.boost.org/doc/libs/1_35_0/libs/smart_ptr/weak_ptr.htm

But you can only create weak_ptr from shared_ptr, since for your objects related to the stack, I am not sure how this will work.

+1
source

It smells of bad design.

I cannot think of a reasonable situation when you do not want to delete the pointer. Here are the situations (unreasonable IMO):

1) static objects of duration. Instead, consider using a singleton mixin (use CRTP to mix a singleton that has an instance () method that returns a copy of the local static shared_ptr <>; local statics are unsafe, so you'll also need an appropriate static mutex if it can be called by multiple threads) . The advantage of using the correct singleton is that your singleton will be destroyed when exiting after other objects that continue to hold shared_ptr <> for it.

2) objects created on the stack. Just don't do it. Instead, create an object on the heap protected by shared_ptr <>. If you need to create shared_ptr <> for an object in different parts of the code (i.e. you cannot take copies from the original shared_ptr <>), then inherit from boost :: enable_shared_from_this <> and get shared_ptr <> from shared_from_this ().

Is there another reason why you want shared_ptr <> that doesn't delete anything?

0
source

All Articles