我正在使用以下框架编写代码:
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 的所有设置,但在退出 correctSettings() 时在 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 的接口(interface)。 谢谢。
最佳答案
在您的第一种方法中,您的 this
只是一个原始指针,但您试图将其转换为具有不同大小、不同结构的“shared_pointer”。
要解决这个问题,您可以尝试使用 boost::enable_shared_from_this
,这将允许您从对象自身的函数中检索对象的共享指针。然后您不必构造另一个 FirstStepBase 对象。
你可以看这里boost_shared_from_this
关于c++ - 将其转换为共享指针并将其作为参数传递给另一个 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44448181/