移动指针的右值引用

时间:2016-01-22 11:12:48

标签: c++ arrays c++11

我在stackoverflow上找到了一种测量程序中已用时间的方法之后用移动语义进行了一些测试,我想问一下它。

我有两个A和B类,B来自A:

class A
{
public:
    A()
    {
        for (int i = 0; i < MAX; i++)
            str[i] = "~~";

        for (int i = 0; i < MAX; i++)
            flt[i] = i;
    }

    std::string str[MAX];
    float flt[MAX];
};

B有两个构造函数定义如下:

B(const A*& a)
{
    for (int i = 0; i < MAX; i++)
        str[i] = a->str[i];

    for (int i = 0; i < MAX; i++)
        flt[i] = a->flt[i];
}



B(A*&& a)
{
    for (int i = 0; i < MAX; i++)
        str[i] = std::move(a->str[i]);

    for (int i = 0; i < MAX; i++)
        flt[i] = std::move(a->flt[i]);
}

其中MAX = 1000

我注意到两个构造函数在速度方面的差异并不大。如果我从第二个构造函数中删除std::move函数,我得到的时间与第一个相同。 我期望第一个构造函数(使用const左值引用作为参数)将两个数组的每个元素复制到B的两个数组中,而第二个构造函数(使用rvalue引用作为参数)将“移动”元素数组。

如果我比较这个

,故事就不会改变
B(A&& a)
{
    for (int i = 0; i < MAX; i++)
        str[i] = std::move(a.str[i]);

    for (int i = 0; i < MAX; i++)
        flt[i] = std::move(a.flt[i]);
}

用这个

B(A a)
{
    for (int i = 0; i < MAX; i++)
        str[i] = a.str[i];

    for (int i = 0; i < MAX; i++)
        flt[i] = a.flt[i];
}

我使用std::move功能无益。 我错过了关于移动语义的东西吗?

1 个答案:

答案 0 :(得分:3)

正如T.C所说 - 移动浮动并没有太大的区别。

尝试使用以下内容进行分析:

class A
{
public:
    A()
        : strings(new std::string[MAX])
        , floats(new float[MAX])
    {
        for (int i = 0; i < MAX; i++)
            strings[i] = "~~";

        for (int i = 0; i < MAX; i++)
            floats[i] = i;
    }

    virtual ~A()
    {
        delete[] strings;
        delete[] floats;
    }

    std::string* strings;
    float* floats;
};

class B : public A
{
public:
    B(){}

    B(B&& other)
    {
        strings = other.strings;
        floats = other.floats;

        other.strings = nullptr;
        other.floats = nullptr;
    }
};

int main()
{
    B b;
    B bb(std::move(b));        
    return 0;
}

正如您所看到的,B&lt; move的构造函数中没有循环,我们只需要使用其他内部函数并将其清零以避免任何双重删除问题。

这绝对不是排列上述代码的最佳方式,只能用作举例说明移动语义。