我试图通过从我的一些方法而不是原始指针返回unique_ptr来更安全一些。但是,在返回指向多态类型的唯一指针时,我有点困惑。
我们如何返回指向派生类类型的基类类型的唯一指针?
此外,作为不太重要的次要问题 - 我是否使用移动构造函数正确地从基类创建派生类?
这是我的最小例子:
// Standard Includes
#include <exception>
#include <memory>
#include <string>
#include <sstream>
//--------------------------------------------------------------------------------------------------
class BaseResult
{
public:
std::string m_x;
virtual ~BaseResult() {};
};
class DerivedResult : public BaseResult
{
public:
int m_y;
DerivedResult()
:
BaseResult()
{}
DerivedResult(const DerivedResult & rhs)
:
BaseResult(rhs)
, m_y (rhs.m_y)
{}
DerivedResult(DerivedResult && rhs)
:
BaseResult(std::move(rhs))
, m_y(rhs.m_y)
{}
DerivedResult(BaseResult && rhs)
:
BaseResult(std::move(rhs))
, m_y()
{
}
~DerivedResult() {}
};
class BaseCalc
{
public:
virtual ~BaseCalc() {}
virtual std::unique_ptr<BaseResult> Calc() const
{
std::unique_ptr<BaseResult> result(new BaseResult);
result->m_x = "Base Calced";
return result;
}
};
class DerivedCalc : public BaseCalc
{
public:
virtual ~DerivedCalc() {}
virtual std::unique_ptr<BaseResult> Calc() const
{
// I need to rely on the base calculations to get the fields relevant to the base
std::unique_ptr<BaseResult> baseResult = BaseCalc::Calc();
// However, I want to perform my addtional calculation relevant to derived, here.
std::unique_ptr<DerivedResult> result(new DerivedResult(std::move(*baseResult)));
result->m_y = 2;
/* Results in error
return result;
*/
return std::move(result); // Is this how we do it?
}
};
//--------------------------------------------------------------------------------------------------
int main()
{
DerivedCalc calculator;
std::unique_ptr<BaseResult> temp = calculator.Calc();
// Cast - Got this part from https://stackoverflow.com/questions/21174593/
std::unique_ptr<DerivedResult> actualResult;
if (DerivedResult * cast = dynamic_cast<DerivedResult *>(temp.get()))
{
actualResult = std::unique_ptr<DerivedResult>(cast, std::move(temp.get_deleter()));
temp.release();
}
else
{
std::exception("Failed to cast to DerivedResult");
}
std::string x = actualResult->m_x;
int y = actualResult->m_y;
return 0;
}
答案 0 :(得分:0)
回答你的第一个问题,“我们如何返回指向派生类类型的基类类型的唯一指针?” (注意std :: make_unique需要c ++ 14):
class DerivedCalc : public BaseCalc
{
public:
virtual ~DerivedCalc() {}
virtual std::unique_ptr<BaseResult> Calc() const
{
// I need to rely on the base calculations to get the fields relevant to the base
std::unique_ptr<BaseResult> baseResult = BaseCalc::Calc();
// However, I want to perform my addtional calculation relevant to derived, here.
std::unique_ptr<BaseResult> result(std::make_unique<DerivedResult>(std::move(*baseResult)));
DerivedResult& derived = static_cast<DerivedResult&>(*result);
derived.m_y = 2;
return result;
}
};
对于您的第二个问题,“我是否使用移动构造函数正确地从基类创建派生类?”,您的版本可以正常工作,但您也可以移动派生数据字段以获得最佳性能:
class DerivedResult : public BaseResult
{
...
DerivedResult(DerivedResult && rhs)
:
BaseResult(std::move(rhs))
, m_y(std::move(rhs.m_y))
{}
...
};