【问题标题】:How to create pointer with `make_shared`如何使用“make_shared”创建指针
【发布时间】:2021-01-04 02:47:51
【问题描述】:

我在看这个页面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并不是更高效,它的目的是更好地处理异常。
  • @super 的主要收获是引用计数器被分配在与创建对象相同的内存块中(单个分配而不是两个)。旧版本中存在异常处理问题。

标签: c++ boost shared-ptr derived-class make-shared


【解决方案1】:

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

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

【讨论】:

  • 或缺少using boost::make_shared;
【解决方案2】:

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

基类与派生类

使用make_shared 创建指针时,您必须使用实际的、派生的、类并为该类的构造函数传递参数。它不知道基类与派生类的关系。您可以通过赋值将它用作指向基类的共享指针(您会注意到,它指向不同的共享指针类型)。

考虑使用标准库。

一个make_shared()函数和一个共享指针类从C++14开始就在标准库中可用,所以你可以这样写:

#include <memory>

// ...

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

到目前为止,标准库共享指针更为常见,因此如果您打算将它们传递给其他人编写的代码,您可能应该更喜欢那些。当然,如果您广泛使用 Boost,这很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多