【发布时间】: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));
我知道,通过这一行,我们基本上是在创建一个名为 americanExercise 的 shared 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