问题描述
我正在查看页面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);
到目前为止,标准库共享指针是最常见的,因此,如果您打算将那些指针传递给其他人编写的代码,则可能应该选择那些。当然,如果您广泛使用Boost,那很好。