将 int 传递给函数,然后使用该 int 创建数组

Passing an int to a function, then using that int to create an array

本文关键字:int 创建 数组 然后 函数      更新时间:2023-10-16

>我正在尝试为我的 openGL 项目创建一个 textureLoader 类,但我无法在我的类构造函数中初始化纹理数组,因为数组不会接受任何东西,除非它是一个 const int。

给你画一幅简单的图画...

myFunction(NUM)
  {
  GLuint textures[NUM];
  }

我过去的失败

myConstructor(const int& num)
  {
   GLuint textures[num] //error: expression must have a constant value
  }

myConstructor(int num)
{
std::vector <GLuint> textures(num);//works but wait
glGenTextures(num, textures) // <--- doesn't work cause vectors. 
}

myConstructor(int num)
{
const int PLEASE_WORK = num;
GLuint textures[PLEASE_WORK]; // doesn't work. 

你的第二个选项很接近,你可以通过调用 .data() 来获取向量的底层数组

myConstructor(int num)
{
    std::vector <GLuint> textures(num);
    glGenTextures(num, textures.data());
}

假设glGenTextures有一个签名,比如

void glGenTextures(int, GLuint*)

我对这个函数了解不多,但要小心谁拥有那个数组。在您的构造函数之后,vector将超出范围,因此我希望glGenTextures会复制它需要的任何内容。否则,如果数组需要持久化

myConstructor(int num)
{
    GLuint* textures = new GLuint[num];
    glGenTextures(num, textures);
}

但是我不确定谁应该清理这段记忆。

相关文章: