简体   繁体   English

使用 reinterpret_cast 向下转换

[英]Downcasting with reinterpret_cast

I am a person, who loves to go deep into nitty-gritty details.我是一个喜欢深入细节的人。 This time I created really simple functionality, which I called "Scenario" (look under for code).这次我创建了非常简单的功能,我称之为“场景”(在下面查找代码)。 First I will present to you my vision of it:首先,我将向您介绍我对它的看法:

struct ScenarioContext
{ virtual ~ScenarioContext() = default; };

struct IScenarioStep
{
    virtual ~IScenarioStep() = default;
    virtual void run( ScenarioContext& ) = 0;
};

struct ScenarioContainer final
{
    std::list<std::unique_ptr<IScenarioStep>> m_scenarioStepList;
};

struct Scenario
{
    explicit Scenario( ScenarioContainer&&, std::unique_ptr<ScenarioContext>&& = nullptr );

    void execute(); // Runs the steps one by one and passes context ref to steps

    std::unique_ptr<ScenarioContext> m_context;
    ScenarioContainer                m_container;
};

And now example "ScenarioStep" implementation:现在示例“ScenarioStep”实现:

struct SimpleContext
    : ScenarioContext
{
    bool isFirstStepDone  = false;
    bool isSecondStepDone = false;
    bool isThirdStepDone  = false;
};

struct ScenarioStep
    : IScenarioStep
{
    void run(ScenarioContext& ctx) override
    {
        auto THE_ISSUE = dynamic_cast<SimpleContext&>(ctx);
    }

};

And here I came to the conclusion, that there is absolutely no way that user/developer might get the wrong type of context.在这里我得出结论,用户/开发人员绝对不可能得到错误类型的上下文。 Is it wrong to use here reinterpret_cast ?在这里使用reinterpret_cast有错吗? If so why?如果是,为什么? The absolute zero cost is so tempting here.绝对零成本在这里非常诱人。

If not reinterpret_cast , what about static_cast ?如果不是reinterpret_cast ,那static_cast呢?

I am really confused about all this "dont's" of tools that we have at our disposal.我真的很困惑我们可以使用的所有这些“不要”的工具。

reinterpret_cast should never be used to cast down the class hierarchy because it doesn't do base pointer adjustment, which is going to bite really hard in case of multiple inheritance. reinterpret_cast永远不应该用于降低 class 层次结构,因为它不进行基指针调整,这在多个 inheritance 的情况下会非常困难。

One can (and should!) use static_cast if they can be certain true object type matches the one expected through some means.如果可以确定真正的 object 类型与通过某种方式预期的类型匹配,则可以(并且应该!)使用static_cast static_cast would still be 0-cost when base pointer adjustments are not needed, and will work correctly when they are required (albeit at a cost).当不需要调整基本指针时, static_cast仍然是 0 成本,并且在需要时可以正常工作(尽管有成本)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM