Search code examples
c++castingundefined-behaviorvoid-pointers

Find a void pointer in an container of MyClass pointers?


I have a pointer void* p that points to a variable of unknown type, as well as a container std::set<MyClass*> c populated with MyClass pointers. Is there some way to find out whether c contains p (i.e. whether it contains a pointer that points to the same memory address as p) without manually looping through the elements in c, that doesn’t cause undefined behavior? (Note that I’m not going to dereference p if I don’t find it in c.)

Also, I assume that casting p to MyClass* would cause undefined behavior if p would point to a variable of a datatype that was not related but to MyClass, but maybe that’s not the case?


Solution

  • I assume that casting p to MyClass* would cause undefined behavior if [..]

    It is pedantically correct that it might cause UB.

    But should probably work in practice (Joy of UB).

    Is there some way to find out whether c contains p [..] without manually looping through the elements in c.

    std::find_if or std::binary_search can be used with appropriate predicate to find it in linear time (std::set::iterator is not a random iterator, so "falsify" binary_search complexity).

    If you can change your container to:

    • std::set<MyClass*, std::less<void>>, then you might safely use std::set::find thanks to transparent comparer.

    • sorted std::vector<MyClass*>, then you might use std::binary_search with correct complexity.