user2425792
user2425792

Reputation:

Is typeid() enough for type safety?

I was wondering if typeid is a "hard enough" criterion for type safety to forego all the usual precautions. Specifically, consider the following code snippet:

class storage
{
private:
    std::map<std::type_index, void*> objects;

public:
    template<typename T>
    void put(T* ptr)
    {
        objects[typeid(*ptr)] = ptr;
    }
};

storage stor;

ClassA* a = new ClassA();
ClassB* b = new ClassB();

stor.put(a);
stor.put(b);

Is it safe to get the objects back from the map using the information from typeid?

template<typename T>
T* storage::get()
{
    return static_cast<T*>(objects[typeid(T)]);
}

Thanks, N.

Upvotes: 1

Views: 316

Answers (1)

Steve Jessop
Steve Jessop

Reputation: 279335

It works, in the sense that a2 has the same value as a.

It's not necessarily "safe". For example, if a pointed to an instance of some derived class of A, then a2 would not be guaranteed to have the same value as a. So safety depends what you mean by "forgo the usual precautions". You can't forgo the "precaution" that if you convert a pointer to void* then you need to convert it back to its original type.

Upvotes: 1

Related Questions