c++ - 如何定义一个在编译时数据未知的 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 ?
解决方案
您可以使用所需的确切类型。允许构造函数将数据写入const
字段:
class Foo {
public:
const float *const m_vertices;
Foo(const float *vertices) : m_vertices(vertices) {}
};
虽然这里不能保证调用者没有非const
指针。如果您想防止这种情况发生,那么您需要复制数据而不仅仅是使用指针。
推荐阅读
- php - 使用不同的控制器和 API 方法访问相同的 url
- angular - HTTPClient Angular
- c++ - 如何增加字符指针?
- javascript - ajax请求,查询数据库,json_encode,成功返回,显示结果
- c - 如何处理用c语言填充结构
- amazon-cloudfront - 如何通过 CloudFront 获取请求的客户端 IP?
- ios - 在 TableView Section header 中添加 UIButton 和 UIImage
- mongodb - MongoDB + Laravel + jenssegers/laravel-mongodb + 更新嵌套子元素
- r - 上传时复制文件并将其粘贴到 www 文件夹位置
- codeigniter - 获取使用 dropzone 上传的文件的文件路径