Your problem comes down to the fact that you have a sequence of basic pointers and you want to use only those elements of the sequence that are a specific derived type.
dynamic_cast certainly works, but in this case it is not needed. If you want to store the necessary pointers in a separate container, you will not need to look for them in a container that also contains other pointers.
std::vector<Observer *> observers {new Observer()};
You still have a container with all pointers, copying observer pointers.
std::vector<BaseFromLibrary *> all {new BaseFromLibrary()}; all.reserve(all.size() + observers.size()); all.insert(all.end(), observers.begin(), observers.end());
Alternatively, you can use something like boost :: join from Boost.Range if you want to iterate over all the elements in separate containers without copying.
You can trivially copy observer pointers without dynamic_cast.
s.observers.insert(observers.begin(), observers.end());
Of course, if that's all you are going to do, you could use s.observers as your source container for observers in the first place.
As an example, your example memory leak program. Avoid manual memory management to prevent these situations.
source share