const void 有什么意义?

2022-01-23 00:00:00 function c constants void c++

显然,可以声明一个返回const void的函数:

Apparently, it is possible to declare a function returning const void:

const void foo()
{
}

g++ 似乎认为 const 很重要,因为以下代码无法编译:

g++ seems to consider the const important, because the following code does not compile:

#include <type_traits>

static_assert(std::is_same<void(), const void()>::value, "const matters");

那么const void有什么实际意义吗?

So does const void have any practical significance?

推荐答案

不是.但是忽略 void 上的 cv 限定或使其出错可能会在编译器实现和最终用户代码方面造成不必要的复杂性.考虑像

Not really. But to ignore cv-qualifications on void or to make them errors could create unnecessary complexity in terms of both compiler implementation and end-user code. Consider templates like

  template<typename T>
  const T ...

没有理由在这种情况下使用 void 成为一种特殊情况(比现在更多),它只会让人头疼.

There's no reason to make using void in that scenario a special case (more than it already is), it would just create headaches.

此外,虽然 const void 没有帮助,但 const void* 也有其用处.

Also, while const void isn't helpful, const void* has its uses.

相关文章