传递/移动C ++ 0x中构造函数的参数 [英] Passing/Moving parameters of a constructor in C++0x

查看:146
本文介绍了传递/移动C ++ 0x中构造函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个n参数的构造函数,使得任何参数可以是一个右值和左值。是否可以支持这种移动语义的右值,而不为每个可能的右值/左值组合写2 ^ n构造函数?

If I have a constructor with n parameters such that any argument to that can be an rvalue and lvalue. Is it possible to do support this with move semantics for the rvalues without writing 2^n constructors for each possible rvalue/lvalue combination?

推荐答案

p>按值取每个值,如下所示:

You take each one by value, like this:

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;
};

参数初始化函数参数将是一个复制构造函数或移动构造函数。

The initialization of the function parameters by the argument will either be a copy-constructor or move-constructor. From there, you just move the function parameter values into your member variables.

请记住:复制和移动语义是由类提供的一种服务,而不是由您。在C ++ 0x中,你不再需要担心如何获得你自己的复制数据;只要求它并让类做它:

Remember: copy- and move-semantics are a service provided by the class, not by you. In C++0x, you no longer need to worry about how to get your own "copy" of the data; just ask for it and let the class do it:

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

注意:你的构造函数只接受值,如何构建自己。从那里,当然,这取决于你把它们移动到你想要的地方。

Note: your constructor only takes in values, those values will figure out how to construct themselves. From there, of course, it's up to you to move them where you want them.

这适用于任何地方。有一个需要副本的功能?在参数列表中创建它:

This applies everywhere. Have a function that needs a copy? Make it in the parameter list:

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中,你可以相当好地模拟它,但它不常见(在我的经验):


In C++03, you could emulate it fairly well, but it wasn't common (in my experience):

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;
};

这篇关于传递/移动C ++ 0x中构造函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆