Search code examples
c++moveshared-ptr

Using a prvalue to create a shared_pointer


I have a class functionCombiner which constructor looks like this

FunctionCombiner::FunctionCombiner(std::vector<std::shared_ptr<valuationFunction>> Inner_) : Inner(std::move(Inner_)), valuationFunction("", 0) //<- Needs to initalize itself even though it gets all data from inner functions.
{
}

In my main class I'm calling it like this:

vector<std::shared_ptr<valuationFunction>> combinedStillFrontFunctions{ stillFrontStock, stillFrontEuropeanCall };
std::shared_ptr<valuationFunction> StillFrontFunctions = std::make_shared<FunctionCombiner>(combinedStillFrontFunctions);

What I would like to be able to do is reduce that to one line by constructing it in place like so

std::shared_ptr<valuationFunction> StillFrontFunctions = std::make_shared<FunctionCombiner>({ stillFrontStock, stillFrontEuropeanCall });

Which the compiler doesn't like. Is there a way to make this work? This works obviously:

FunctionCombiner StillFrontFunctions({ stillFrontStock, stillFrontEuropeanCall });

But I need it to be a shared pointer.


Solution

  • (Shorting some names to make the example readable w/o horizontal scrollbars. You should consider doing the same...)

    Passing {x,y} to make_shared() is attempting to forward a brace-enclosed initializer list, not to initialize the value in the shared pointer, but the temporary object its constructor takes. It's not something that can be forwarded since it's not a full expression on its own. So make a temporary vector with those values:

    ... = make_shared<FunComb>(vector<shared_ptr<valFun>>{FS, FEC});
    

    Another approach may be to change FunComb's constructor to be a (or add a new) variadic constructor, removing the need to pass in a vector just to hold the inputs.