首页 > 解决方案 > 如何定义一个在编译时数据未知的 const 数组

问题描述

我想将网格的顶点数据存储在一个类中。每个实例都有一个浮点数组,并且可以通过返回数组指针的 getter 访问。数组的数据应该是常量,数组本身也是如此。所以我的第一个想法是这样声明成员:

const float * const m_vertices;  // const pointer to const floats

问题是在编译时不知道实际数据(从文件加载,程序生成......)

有没有办法确保数据保持不变,除非它被初始化(例如在构造函数中)?

编辑:我尝试了约瑟夫提出的建议:

//Mesh class
Mesh::Mesh(const float *vertices)
: m_vertices(vertices)
{
}

//creation of data
int size = 10; //this can't be const because the number of vertices is not known at compile time 
float arr[size]; //error : "size" is not const
for (int i = 0; i < 10; i++) {
    arr[i] = i;
}
Mesh m = Mesh(arr); //this apparently works... But the constructor is expecting a const float *. Here i'm giving a float *. Why does this works ?

标签: c++arrays

解决方案


您可以使用所需的确切类型。允许构造函数将数据写入const字段:

class Foo {
  public:
    const float *const m_vertices;
    Foo(const float *vertices) : m_vertices(vertices) {}
};

虽然这里不能保证调用者没有非const指针。如果您想防止这种情况发生,那么您需要复制数据而不仅仅是使用指针。


推荐阅读