【发布时间】:2017-06-09 02:07:24
【问题描述】:
我正在使用以下框架编写代码:
class IFirstStep // abstract interface
{
public:
virtual commonMethod1() = 0;
...
};
class FirstStepBase : public IFirstStep // Jobs common to all FirstStep's
{
public:
FirstStepBase() {}
commonMethod1() override;
...
protected:
CommonMembers;
void correctSettings()
{
somePreparations;
auto smartPtr = static_cast<std::shared_ptr<IFirstStep>>(this);
SecondStep secondStep(smartPtr);
some calculations using secondStep;
reassignment of some of commonMembers;
}
};
class FirstStep1 : public FirstStepBase
{
public:
FirstSiep1(bool fineTune)
{
commonMembers = initilizeSettings();
if (fineTune)
correctSettings();
}
private:
CommonMembers initilizeSettings() {calculate and assign commonMembers;}
};
class FirstStep2 : public FirstStepBase
...
class FirstStepN : public FirstStepBase
...
class SecondStep
{
public:
SecondStep(std::shared_ptr<IFirstStep> & firstStep) : m_firstStep(firstStep) {}
some methods which use firstStep and return some results;
firstStep itself is not changed;
};
correctSettings() 被完美执行,纠正了 FirstStep1 的所有设置,但在 MS VS 调试器中在从正确设置() 退出时崩溃:
File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp
Line: 888
Expression: _CrtIsValidHeapPointer(block)
看起来问题是由强制转换引起的 - 即使在强制转换后执行退出,代码也会崩溃。 MS VS 编译器不接受其他类型的转换,包括指针转换。但是,如果将 correctSettings() 更改如下并将适当的构造函数添加到 FirstStepBase 中,则事情会完美运行
void correctSettings()
{
std::shared_ptr<IFirstStep> smartPtr
= <std::make_shared<FirstStepBase>>(commonMembers);
SecondStep secondStep(smartPtr);
some calculations using secondStep;
reassignment of some of commonMembers;
}
我将非常感谢解释为什么第一种方法会失败,是否可以在代码中使用 this 指针而不是生成额外的 FirstStepBase 对象?请假设无法更改 SecondStep 的接口。 谢谢。
【问题讨论】:
标签: c++ pointers arguments this