Remove from std :: set <shared_ptr <T>> with T *

I have a set of common pointers:

std::set<boost::shared_ptr<T>> set; 

And a pointer:

 T* p; 

I would like to effectively remove the set element equal to p , but I cannot do this with any of the elements of the set or with any of the standard algorithms, since T* is completely different type before boost::shared_ptr<T> .

A few approaches that I can think of are as follows:

  • somehow create a new shared_ptr from a pointer that won't own the allocated memory (perfect solution, but I don't see how to do this)
  • wrapping / reimplementing shared_ptr so that I can do the above
  • just does my own binary set search
+4
source share
3 answers

Build a shared_ptr<T> from T using null_deleter (see boost: shared_ptr FAQ ).

 struct null_deleter { void operator()(void const *) const { } }; size_t remove_ptr_from_set(std::set<boost::shared_ptr<T>> &set, X* x) { shared_ptr<X> px(x, null_deleter()); return set.erase(px); } 

Thus, the types are compatible, and you don’t have to worry about your temporary shared_ptr deleting any object.

Or, as one of the comments says, if you can change T to inherit from enable_shared_from_this , you can get the correct common ptr from your object.

+9
source

If the reason for using a set is that you need to efficiently find pointers of type T, then the obvious answer is not to create a set of common pointers! Instead, wrap the set in a class that controls the lifetime of the pointers contained in the set.

+1
source

You can use boost::ptr_set if you want the set to own the objects, or boost::reference_wrapper if you want the set to keep references to them. If you use shared_ptr in one place in your code, you will have to use it in all places or jeopardize terrible failures (dangling pointers, already deleted objects, etc.). The exception is weak_ptr , a pointer that points to an object stored in shared_ptr but without ownership.

+1
source

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


All Articles