如何在不违反 C++ 核心准则的情况下将整数转换为 void*?

2021-12-19 00:00:00 opengl c++

这有效,但也会导致不要使用 reinterpret_cast (type.1)"警告:

This works but also results in "Don't use reinterpret_cast (type.1)" warning:

glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 8,
  reinterpret_cast<void*>(sizeof(GLfloat) * 3));

这不会编译:

glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 8,
  static_cast<void*>(sizeof(GLfloat) * 3));

这不会编译:

glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 8,
  dynamic_cast<void*>(sizeof(GLfloat) * 3));

这显然有效,但在 C++ 中似乎是一个很大的禁忌(不要使用 C 风格的强制转换(type.4)")

This obviously works but seems to be a big no-no in C++ ("Don't use C-style casts (type.4)")

glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 8,
  (void*)(sizeof(GLfloat) * 3));

我应该忽略关于 reinterpret_cast 的警告吗?

Should i just ignore the warning about the reinterpret_cast?

推荐答案

当您进行低级编程时,您偶尔会不得不做一些 C++ 核心指南规定您不应该做的事情.因此,只需执行这些操作,要么接受警告",要么关闭该特定指南(可能在每个文件的基础上).

When you're doing low-level programming, you will occasionally have to do things that the C++ core guidelines say you shouldn't do. So just do them and either live with the "warning" or turn off that specific guideline (possibly on a per-file basis).

话虽如此,需要这种特殊的低级欺骗完全是因为 OpenGL 在其顶点规范 API 中的愚蠢.该值应该是某种整数字节偏移量,而不是转换为另一方将转换回偏移量的指针的偏移量.

That having been said, the need for this particular bit of low-level fudgery is solely because of OpenGL's stupidity in its vertex specification API. That value ought to be an integer byte offset of some sort, not an offset cast to a pointer which the other side will cast back to an offset.

所以最好完全避免使用糟糕的 API.使用单独的属性格式规范,而不是旧式的glVertexAttribPointer.它几乎在各个方面都优越.它会将您的代码从:

So it would be better to just avoid the bad API altogether. Use separate attribute format specification rather than the old-style glVertexAttribPointer. It's superior in pretty much every way. It will turn your code from:

glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 8,
  reinterpret_cast<void*>(sizeof(GLfloat) * 3));

glVertexAttribFormat(1, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 3); //Offset specified as integer.
glVertexAttribBinding(1, 0); //You seem to be using multiple attributes with a stride, so they should use the same buffer binding.

//Some later point when you're ready to provide a buffer.

glBindVertexBuffer(0, buffer_obj, 0, sizeof(GLfloat) * 8); //Stride goes into the buffer binding.

看,根本没有演员.

遗憾的是,glDrawElements 函数系列没有替代方案,因此您仍会收到此警告.

Unfortunately, there are no alternatives for the glDrawElements family of functions, so you're still going to get this warning.

相关文章