比较 std::unique_ptr 指向的基础(派生)类型

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

我正在编写单元测试来练习涉及工厂的各种代码路径 class。

工厂returns一个std::unique_ptr到一个基本类型:

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>();
    }
}

所以在测试中我想确保返回正确的类型(工厂是剪切和粘贴错误的温床)。

有没有办法检查返回的类型? 这:EXPECT_TRUE(typeid(Derived1), typeid(type.get()); 是错误的,因为 type.get()Base 而不是传入的 rtype

您需要使用 RTTI。使用时类型被擦除为Base

您可以进行动态转换以获得正确的类型,例如:

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

如果 dynamic_cast 失败(类型不是 Derived1)dynamic_cast 将 return 一个 nullptr.

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() ) 将获取基指针的 typeid,即 get() 声明为返回的类型。要获得指向对象的真实动态类型,无论是什么,您都应该取消引用指针:

typeid( *type.get() )