简体   繁体   中英

How to create pointer with `make_shared`

I was looking at this page http://www.bnikolic.co.uk/blog/ql-fx-option-simple.html , on the implementation of shared_pointer.

There is one such line -

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

I understand that, with this line, we are basically creating a shared pointer of name americanExercise , which is pointing to an object of class Exercise .

But I was wondering how can this line be rewritten with make_shared , as it is accepted that make_shared is more efficient way to define pointer. Below is my try -

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

However this fails with the error -

error: use of undeclared identifier 'make_shared'
     shared_ptr<Exercise> americanExercise = make_shared<Exercise>(AmericanExercise(settlementDate, in.maturity));

Could you please help me to understand the use of the make_shared , in this case.

Many thanks for your help.

You seem to be missing the namespace from your second example. Also you can construct your derived type in make_shared .

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

Two points in addition to @Caleth's valid answer:

The base class vs. the derived class

When creating a pointer with make_shared , you have to use the actual, derived, class and pass arguments for a constructor of that class. It doesn't know about base-class vs derived-class relations. You get to use it as a shared pointer to the base class via the assignment (which, you will note, is to a different shared pointer type).

Consider using the standard library.

A make_shared() function and a shared pointer class are available in the standard library since C++14, so you could write:

#include <memory>

// ...

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

by now, standard-library shared pointers are by far the more common, so if you intend to pass those around to code written by others, you should probably prefer those. Of course, if you're using Boost extensively than this is fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM