如何使用 auto 声明一个 void 指针?
How to declare a void pointer using auto?
我们曾经像这样声明一个空指针而不使用auto
。
void* ptr = nullptr;
我们应该如何使用 auto
做同样的事情?我们应该使用哪一个?或者也许还有其他更好的方法?
auto ptr = (void*)nullptr;
auto ptr = (void*)0;
This is not a question about coding style. Just want to know IF we need to use auto
, what should be the best way.
auto ptr = static_cast<void*>(nullptr);
正如您可能知道的那样,C 风格的转换不是很好,因为它们基本上可以转换任何东西,而 static_cast 可以防止丢弃 const,而疯狂的东西 reinterpret_cast 允许。
如果您在声明期间已经知道类型,则有 LITTLE 使用 auto
的理由。正如其他人所说,原始样式应该是您想要的,这样可以使您的代码简洁明了。
void* ptr = nullptr;
如果出于某种原因您要使用 auto
,例如出于好奇或您无法控制的编码风格,或者您是 auto
的超级粉丝,则 static_cast<void*>
作为Nir 的回答中提到的比使用 C 风格转换更好的选择,后者可能会在运行时失败。
auto ptr = static_cast<void*>(nullptr);
参考
- What is the difference between static_cast<> and C style casting?
没有强制转换的备选方案:
using void_ptr = void*;
auto ptr = void_ptr{};
或
auto ptr = std::add_pointer_t<void>{};
我们曾经像这样声明一个空指针而不使用auto
。
void* ptr = nullptr;
我们应该如何使用 auto
做同样的事情?我们应该使用哪一个?或者也许还有其他更好的方法?
auto ptr = (void*)nullptr;
auto ptr = (void*)0;
This is not a question about coding style. Just want to know IF we need to use
auto
, what should be the best way.
auto ptr = static_cast<void*>(nullptr);
正如您可能知道的那样,C 风格的转换不是很好,因为它们基本上可以转换任何东西,而 static_cast 可以防止丢弃 const,而疯狂的东西 reinterpret_cast 允许。
如果您在声明期间已经知道类型,则有 LITTLE 使用 auto
的理由。正如其他人所说,原始样式应该是您想要的,这样可以使您的代码简洁明了。
void* ptr = nullptr;
如果出于某种原因您要使用 auto
,例如出于好奇或您无法控制的编码风格,或者您是 auto
的超级粉丝,则 static_cast<void*>
作为Nir 的回答中提到的比使用 C 风格转换更好的选择,后者可能会在运行时失败。
auto ptr = static_cast<void*>(nullptr);
参考
- What is the difference between static_cast<> and C style casting?
没有强制转换的备选方案:
using void_ptr = void*;
auto ptr = void_ptr{};
或
auto ptr = std::add_pointer_t<void>{};