简体   繁体   English

使用prvalue创建shared_pointer

[英]Using a prvalue to create a shared_pointer

I have a class functionCombiner which constructor looks like this我有一个 class functionCombiner,它的构造函数看起来像这样

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:在我的主要 class 中,我这样称呼它:

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.但我需要它是一个共享指针。

(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.{x,y}传递给make_shared()是试图转发一个用大括号括起来的初始化列表,而不是初始化共享指针中的值,而是初始化它的构造函数采用的临时 object。 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.另一种方法可能是将FunComb的构造函数更改为(或添加新的)可变参数构造函数,从而无需传递vector来保存输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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