简体   繁体   English

如何使用函数的输出初始化 const 数组结构字段?

[英]How do I initialise a const array struct field with the output of a function?

I have a struct that contains a const array, and would like to initialise it to specific values upon construction.我有一个包含 const 数组的结构,并希望在构造时将其初始化为特定值。 Unfortunately, its contents depend on several parameters which are passed into the constructor as parameters, and require a function to compute the contents of the array.不幸的是,它的内容取决于作为参数传递给构造函数的几个参数,并且需要一个函数来计算数组的内容。

What I'd ideally like to do looks something like this:我理想中想做的事情是这样的:

struct SomeType {
    const unsigned int listOfValues[32];

    unsigned int[32] processParameters(unsigned int parameter) {
        unsigned int arrayValues[32];
        for(int i = 0; i < 32; i++) {
            arrayValues[i] = i * parameter;
        }
        return arrayValues;
    }

    SomeType(unsigned int parameter) : listOfValues(processParameters(parameter)) {

    }
};

Of course there are several issues here (returning an array from a function is not possible, data type mismatches, etc).当然这里有几个问题(从函数返回数组是不可能的,数据类型不匹配等)。 However, is there any way this is possible?然而,有没有什么办法可能的吗?

I've seen other similar questions suggest using a std::vector for this, but the heap allocation(s) this incurs is something my performance budget can't afford.我已经看到其他类似的问题建议为此使用 std::vector,但是由此产生的堆分配是我的性能预算无法承受的。

As Nathan suggested you should change the raw array with an std::array .正如 Nathan 建议的那样,您应该使用std::array更改原始std::array This way you still have the benefit of stack allocation but now you can initialize from a copy.这样您仍然可以享受堆栈分配的好处,但现在您可以从副本进行初始化。

using MyArray = std::array<unsigned int, 32>;

const MyArray listOfValues;

MyArray processParameters(unsigned int parameter) {

    MyArray arrayValues;

    for(int i = 0; i < 32; i++) {
        arrayValues[i] = i * parameter;
    }
    return arrayValues;
}

I removed the const from the array data type since it's not necesary because your array is const already, also with const unsigned int you wouldn't be able to set the values of arrayValues at run time.我从数组数据类型中删除了 const ,因为它不是必需的,因为您的数组已经是 const ,而且使用 const unsigned int 您将无法在运行时设置arrayValues的值。

Does this serve your purpose?这是否符合您的目的? No heap allocations that I can see.没有我能看到的堆分配。

struct SomeType {
    const unsigned int *listOfValues;

    const unsigned int * processParameters(unsigned int parameter) {
        for(int i = 0; i < 32; i++) {
            _listOfValues[i] = i * parameter;
        }
        return _listOfValues;
    }

    SomeType(unsigned int parameter) :
        listOfValues(processParameters(parameter))
    {

    }
    private:
        unsigned int _listOfValues[32];
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM