你可以按值来获取每一项,如下所示:
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;
};