在构造函数中将对象移动到成员

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

我有几个类,其中的对象是另一个类的成员。

class ARX;
class PID;
class Simulation
{
    ARX arx;
    PID pid;
};

我想在“外部”构造所有成员,然后将它们移动到类中。像这样:

    ARX arx(...);
    PID pid(...);

    Simulation sim(arx, pid); // arx and pid are now empty/default/whatever

平原

Simulation(ARX, PID)
无论如何都会制作副本,这破坏了移动的全部意义。

我发现实际上似乎在工作的一个构造函数是

Simulation(ARX& a, PID& p) : arx(std::move(a)), pid(std::move(p)) {}

但是,非 const 引用可能会阻止我使用 temporary?

Simulation(ARX&&, PID&&)
给出了unhelpful
none of the 4 overloads could convert all the argument types
.

请告诉我实施这种移动的正确方法是什么。

c++ move-semantics
© www.soinside.com 2019 - 2024. All rights reserved.