Reputation: 332
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:
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
? If so why? The absolute zero cost is so tempting here.
If not reinterpret_cast
, what about static_cast
?
I am really confused about all this "dont's" of tools that we have at our disposal.
Upvotes: 1
Views: 149
Reputation: 62613
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.
One can (and should!) use static_cast
if they can be certain true object type matches the one expected through some means. 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).
Upvotes: 9