c++boostshared-ptrderived-classmake-shared

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.


Solution

  • 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);