如何使用"make_shared"创建指针

How to create pointer with `make_shared`

本文关键字:quot 创建 指针 shared make 何使用      更新时间:2024-03-29

我在看这个页面http://www.bnikolic.co.uk/blog/ql-fx-option-simple.html,关于shared_pointer的实现。

有一条这样的线路——

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

我知道,通过这一行,我们基本上创建了一个名为americanExerciseshared pointer,它指向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的用法吗。

非常感谢你的帮助。

第二个示例中似乎缺少名称空间。此外,您还可以在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,这也没关系。