微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何用`make_shared`创建指针

如何解决如何用`make_shared`创建指针

我正在查看页面http://www.bnikolic.co.uk/blog/ql-fx-option-simple.html,该页面有关shared_pointer的实现。

有这样一条线-

boost::shared_ptr<Exercise> americanExercise(new AmericanExercise(settlementDate,in.maturity));

我知道,这一行基本上是在创建名称shared pointer的{​​{1}},它指向类americanExercise的对象。

但是我想知道如何用Exercise重写此行,因为人们普遍认为make_shared是定义指针​​的更有效方法。以下是我的尝试-

make_shared

但是这失败并显示错误-

shared_ptr<Exercise> americanExercise = make_shared<Exercise>(AmericanExercise(settlementDate,in.maturity)); 

在这种情况下,请您帮助我了解error: use of undeclared identifier 'make_shared' shared_ptr<Exercise> americanExercise = make_shared<Exercise>(AmericanExercise(settlementDate,in.maturity)); 用法

非常感谢您的帮助。

解决方法

您似乎在第二个示例中缺少名称空间。您也可以在make_shared中构造派生类型。

boost::shared_ptr<Exercise> americanExercise = boost::make_shared<AmericanExercise>(settlementDate,in.maturity); 
,

除了@Caleth的有效答案外,还有两点:

基类与派生类

使用make_shared创建指针时,必须为该类的构造函数使用实际的派生类和传递参数。它不了解基类与派生类的关系。您可以通过分配将它用作指向基类的共享指针(您将注意到,它是另一种共享指针类型)。

考虑使用标准库。

自C ++ 14起,标准库中提供了make_shared()函数和共享指针类,因此您可以编写:

#include <memory>

// ...

std::shared_ptr<Exercise> americanExercise = 
   std::make_shared<AmericanExercise>(settlementDate,in.maturity); 

到目前为止,标准库共享指针是最常见的,因此,如果您打算将那些指针传递给其他人编写的代码,则可能应该选择那些。当然,如果您广泛使用Bo​​ost,那很好。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。