在constexpr构造函数中复制数组

时间:2014-11-22 23:29:15

标签: c++ arrays c++11 copy-constructor constexpr

我用constexpr拷贝构造函数编写了一个类。 (这是一个结构,使其更简单。)其中一个字段是一个数组。我也要复制它。

struct Foo
{
    static constexpr int SIZE = 4;
    constexpr Foo() = default;
    constexpr Foo(const Foo &foo) :
            arr{foo.arr[0], foo.arr[1], foo.arr[2], foo.arr[3]},
            bar(foo.bar+1) {}
    int arr[SIZE] = {0, 0, 0, 0};
    int bar = 0;
};

我的版本有效,但不可扩展。如果我改变SIZE,我必须修改构造函数。另外,代码看起来很难看。

在构造函数中复制数组是否有更好的方法?构造函数必须是constexpr

3 个答案:

答案 0 :(得分:3)

您可以使用std :: array。由于它是一种聚合类型,我相信这会起作用。

答案 1 :(得分:3)

在C ++ 14中,您只需使用循环来复制数组:

constexpr Foo(const Foo &foo)
    : bar(foo.bar + 1)
{
    for (int i = 0; i < SIZE; ++i)
        arr[i] = foo.arr[i];
}

这并不意味着你应该这样做。我建议改用std::array。例如,如果arr是一个具有非平凡初始化的某个类类型的数组,它将被默认初始化然后被复制,从而浪费性能,而不是使用std::array时的复制初始化和默认值复制构造函数。

答案 2 :(得分:2)

你可以像在C ++ 11中那样只复制数组

template <int LENGTH>
constexpr bool copy_array(const char (&from)[LENGTH + 1], char (&to)[LENGTH], int index)
{
    return index < LENGTH ?  (to[index] = from[index], copy_array(from, to, ++index)) : false;
}

constexpr char src[] = "ab";
char dest[2];
copy_array(src, dest, 0);

编辑: 在您的上下文中,您可以执行以下操作:

#include <iostream>
#include <type_traits>
#include <array>
#include <utility>

struct Foo
{
    static constexpr int SIZE = 4;
    constexpr Foo() = default;
    constexpr Foo(const Foo &foo) :
            arr{foo.arr},
            bar(foo.bar + 1) {}
    std::array<int, SIZE> arr = {{0, 0, 0, 0}};
    int bar = 0;
};

int main()
{
    constexpr Foo foo1;
    constexpr Foo foo2(foo1);

    std::cout << foo1.bar << std::endl;
    std::cout << foo2.bar << std::endl;

    return 0;
}
相关问题