C ++ 03通过构造函数将向量移动到类成员中(移动语义) [英] C++03 moving a vector into a class member through constructor (move semantics)

查看:204
本文介绍了C ++ 03通过构造函数将向量移动到类成员中(移动语义)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只能访问C ++ 03,我经常想将一个向量移动到一个函数的方式,你可以在C ++ 11中做到这一点。问题如何做,不要混淆用户的代码太多。所以我的问题是程序员是如何在C ++ 11之前做的。

I only have access to C++03 and I often want to move a vector into a function the way you can do it in C++11. The question how to do it not to confuse the user of the code too much. So my question is how did programmers do it before C++11.

我知道矢量可以使用交换函数移动。所以这里是我想出来的:

I know that vector can be "moved" using swap function. So here is what I have come up with:

class Foo
{
public:
    Foo(std::vector<int>& vec)
    {
        using std::swap;
        swap(vec, m_vec);   // "move" vec into member vector
    }

private:
    std::vector<int> m_vec;
};

// usage:
std::vector<int> v(100, 1337);
Foo foo(v);
// v.empty() == true

对于用户来说,他们的向量将被移动到类Foo中是不明显的。有这样的问题的最佳实践解决方案吗?提前感谢!

The problem with this approach is that its not evident to the user that their vector will be moved into the class Foo. Is there a best practice solution to this kind of problem? Thanks in advance!

推荐答案

您可以定义一个包装引用的类型和一个函数来包装它,在调用站点移动语义。

You could define a type wrapping a reference, and a function to wrap it, to give something similar to move semantics at the call site. Something along the lines of

template <typename T> struct move_ref {
    explicit move_ref(T & ref) : ref(ref) {}
    T & ref;
};

template <typename T> move_ref<T> move(T & t) {return move_ref<T>(t);}

Foo(move_ref< std::vector<int> > vec)
{
    using std::swap;
    swap(vec.ref, m_vec);   // "move" vec into member vector
}

Foo foo(move(v));

或者,Boost有,以允许没有C ++ 11的移动语义。

Alternatively, Boost has a library to allow move semantics without C++11.

这篇关于C ++ 03通过构造函数将向量移动到类成员中(移动语义)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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