我试图通过从我的一些方法返回 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;
}
最佳答案
回答您的第一个问题,“我们如何返回指向派生类类型的基类类型的唯一指针?” (注意 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))
{}
...
};
关于c++ - 将 unique_ptr 返回到多态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44462388/
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳
我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s
我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain
如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:
我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我
我有一个数组数组,想将元素附加到子数组。+=做我想做的,但我想了解为什么push不做。我期望的行为(并与+=一起工作):b=Array.new(3,[])b[0]+=["apple"]b[1]+=["orange"]b[2]+=["frog"]b=>[["苹果"],["橙子"],["Frog"]]通过推送,我将推送的元素附加到每个子数组(为什么?):a=Array.new(3,[])a[0].push("apple")a[1].push("orange")a[2].push("frog")a=>[[“苹果”、“橙子”、“Frog”]、[“苹果”、“橙子”、“Frog”]、[“苹果”、“
我使用的是遗留数据库,所以我无法控制数据模型。他们使用了很多多态链接/连接表,就像这样createtableperson(per_ident,name,...)createtableperson_links(per_ident,obj_name,obj_r_ident)createtablereport(rep_ident,name,...)其中obj_name是表名,obj_r_ident是标识符。因此链接的报告将按如下方式插入:insertintoperson(1,...)insertintoreport(1,...)insertintoreport(2,...)insertint