在 C++0x 中传递/移动构造函数的参数

2024-02-16

如果我有一个带有 n 个参数的构造函数,那么该构造函数的任何参数都可以是右值和左值。是否可以通过右值的移动语义来支持这一点,而无需为每个可能的右值/左值组合编写 2^n 构造函数?


你可以按值来获取每一项,如下所示:

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;
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C++0x 中传递/移动构造函数的参数 的相关文章

随机推荐