如何在没有警告的情况下“安全”地施放至void**?

问题描述 投票:0回答:1

我正在使用 SDL 创建一个简单的游戏。我需要使用 SDL_LockTexture 函数,所以我编写了以下代码。

uint8_t* pixels = nullptr;
int pitch = 0;
SDL_LockTexture(textures[texture_index], nullptr, reinterpret_cast<void**>(&pixels), &pitch);

但是,clang-tidy警告我不要使用reinterpret_cast。所以我尝试用 static_cast 替换它,但是 static_cast 给了我一个编译错误。代码本身工作正常,但警告很烦人。如何以 C++ 风格安全地转换为 void**?

c++ casting
1个回答
0
投票

创建一个

void* vpixels
。将指向该函数的指针传递给该函数。

然后将

void*
静态转换为像素指针类型。

您可以编写一个帮助程序来为您执行此操作:

template<class T>
struct out_ptr{
  T** out;
  void* temp=nullptr;
  out_ptr(T*& p):out(&p){}
  operator void**()&&{return &temp;}
  ~out_ptr(){
    *out=static_cast<T*>(temp);
  }
};

用途:

SDL_LockTexture(textures[texture_index], nullptr, out_ptr{pixels}, &pitch);

这依赖于 CTAD:没有它,您将需要一个辅助函数,而不是直接调用构造函数。

© www.soinside.com 2019 - 2024. All rights reserved.