Comparing underlying (derived) types pointed-to by std::unique_ptr

226 views Asked by At

I am writing unit tests to exercise various code paths involving a factory class.

The factory returns a std::unique_ptr to a base type:

class Base {};
class Derived1 : public class Base {};
class Derived2 : public class Base {};

std::unique_ptr<Base> Type::Factory(enum rtype) const {
    switch(rtype) {
        case d1: return std::make_unique<Derived1>();
        case d2: return std::make_unique<Derived2>();
        default: return std::make_unique<Derived1>();
    }
}

So in the test I want to ensure that the correct type is returned (factories are breeding ground for cut'n'paste bugs).

Is there a way of checking what type is returned? This: EXPECT_TRUE(typeid(Derived1), typeid(type.get()); is false because the type.get() is that of Base and not the rtype that was passed in.

2

There are 2 answers

0
underscore_d On BEST ANSWER

This: EXPECT_TRUE(typeid(Derived1), typeid(type.get()); is false because the type.get() is that of Base and not the rtype that was passed in.

typeid( type.get() ) will get the typeid of the base pointer, i.e. the type that get() is declared as returning. To get the real dynamic type of the pointed-to object, whatever that may be, you should dereference the pointer:

typeid( *type.get() )

0
Mikael H On

You need to use RTTI. The type is erased to Base when used.

You can do a dynamic cast to get the proper type, something like:

EXPECT_FALSE(dynamic_cast<Derived1*>(type.get()) == nullptr)

If dynamic_cast fails (type is not of Derived1) dynamic_cast will return a nullptr.