如何用`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,那很好。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...