你按值取每一个,像这样:
struct foo
{
foo(std::string s, bar b, qux q) :
mS(std::move(s)),
mB(std::move(b)),
mQ(std::move(q))
{}
std::string mS;
bar mB;
qux mQ;
};
参数对函数参数的初始化将是复制构造函数或移动构造函数。从那里,您只需将函数参数值移动到您的成员变量中。
记住:复制和移动语义是由班级提供的服务,而不是你自己提供的服务。在 C++0x 中,您不再需要担心如何获取自己的数据“副本”;只是要求它,让班级去做:
foo f("temporary string is never copied", bar(), quz()); // no copies, only moves
foo ff(f.mS, f.mB, f.mQ); // copies needed, will copy
foo fff("another temp", f.mB, f.mQ); // move string, copy others
注意:您的构造函数只接受值,这些值将弄清楚如何构造自己。当然,您可以从那里将它们移动到您想要的位置。
这适用于任何地方。有需要复制的功能吗?使其在参数列表中:
void mutates_copy(std::string s)
{
s[0] = 'A'; // modify copy
}
mutates_copy("no copies, only moves!");
std::string myValue = "don't modify me";
mutates_copy(myValue); // makes copy as needed
mutates_copy(std::move(myValue)); // move it, i'm done with it
在 C++03 中,你可以很好地模拟它,但它并不常见(根据我的经验):
struct foo
{
foo(std::string s, bar b, qux q)
// have to pay for default construction
{
using std::swap; // swaps should be cheap in any sane program
swap(s, mS); // this is effectively what
swap(b, mB); // move-constructors do now,
swap(q, mQ); // so a reasonable emulation
}
std::string mS;
bar mB;
qux mQ;
};