其中哪些是std::move的正确用法?

问题描述 投票:1回答:1

我想把我的代码改成用std::move取值而不是用引用来传递一个向量,因为我收集到这样做会更有效率。不过我看到了不同的方法,一种是让构造函数按值传递,并在构造函数中使用std::move,另一种方法是用std::move初始化类,并让构造函数取一个rvalue(我没看错吧?)。下面举一些例子。

方法1:

构造函数。

StatisticsCompiler::StatisticsCompiler(std::vector<Wrapper<StatisticsMC>> Inner_) :Inner(std::move(Inner_))
{
}

在main中。

vector<Wrapper<StatisticsMC>> gathererArray{ meanGatherer, absQuantileGatherer, relVaRGatherer, relESGatherer };
StatisticsCompiler gathererCombiner(gathererArray);

方法2:构造函数:在main:中。

构造函数:在main:方法2。

StatisticsCompiler::StatisticsCompiler(std::vector<Wrapper<StatisticsMC>>&& Inner_) :Inner(Inner_)
{
}

main:

vector<Wrapper<StatisticsMC>> gathererArray{ meanGatherer, absQuantileGatherer, relVaRGatherer, relESGatherer };
StatisticsCompiler gathererCombiner(std::move(gathererArray));

这其中到底是有什么区别还是一回事,第一种方法在main中 "看起来 "比较漂亮,但第二种方法是我从学习rvalues中直观理解的工作方式。如果从性能上来说,它们是完全一样的,那么标准做法是什么?

c++ move rvalue
1个回答
7
投票
StatisticsCompiler::StatisticsCompiler(std::vector<Wrapper<StatisticsMC>> Inner_) :Inner(std::move(Inner_))

这个构造函数通过取值来获取参数。参数可以从lvalue参数中复制,也可以从rvalue中移动。这种从lvalue复制和从rvalue移动之间选择的能力,加上简单的特点,是为什么推荐使用这种方法。

成员总是从那个复制或移动的参数中移动。

StatisticsCompiler gathererCombiner(gathererArray);

你传递了一个lvalue,因此参数被复制了。你可以通过传递一个rvalue来代替使用move构造函数。

StatisticsCompiler gathererCombiner(std::move(gathererArray));

或者你甚至可以使用一个prvalue:

 StatisticsCompiler gathererCombiner({
    meanGatherer,
    absQuantileGatherer,
    relVaRGatherer,
    relESGatherer,
 });

StatisticsCompiler::StatisticsCompiler(std::vector<Wrapper<StatisticsMC>>&& Inner_) :Inner(Inner_)

这个构造函数只接受rvalue参数。这不像第一个建议那样灵活,因为它也可以接受l值。

这种方法总是将参数复制到成员中。你可能想用移动来代替。

Inner(std::move(Inner_))

结论: 当你想存储一个作为参数的对象时,那么通过值传递(第一个例子)是不错的默认选择。如果你之后不需要传递的参数,那么你可以选择从它那里移动。

© www.soinside.com 2019 - 2024. All rights reserved.