What is const void?

C++C++11C++14

C++ Problem Overview


The description of [std::is_void][1] states that:

> Provides the member constant value that is equal to true, if T is the type void, const void, volatile > void, or const volatile void.

Then what could be const void, or a volatile void ?

[This answer][2] states that const void return type would be invalid (however compiles on VC++ 2015)

const void foo() { }

If by standard, const void is invalid (VC being wrong) - then what is const void? [1]: http://en.cppreference.com/w/cpp/types/is_void [2]: https://stackoverflow.com/a/28707034/264325

C++ Solutions


Solution 1 - C++

const void is a type which you can form a pointer to. It's similar to a normal void pointer, but conversions work differently. For example, a const int* cannot be implicitly converted to a void*, but it can be implicitly converted to a const void*. Likewise, if you have a const void* you cannot static_cast it to an int*, but you can static_cast it to a const int*.

const int i = 10;
void* vp = &i;                           // error
const void* cvp = &i;                    // ok
auto ip = static_cast<int*>(cvp);        // error
auto cip = static_cast<const int*>(cvp); // ok

Solution 2 - C++

As void, const void is a void type. However, if const void is a return type, the const is meaningless (albeit legal!), because [expr]/6:

> If a prvalue initially has the type “cv T”, where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis.

However, it is a valid type itself and occurs in e.g. C-standard library functions, where it's used to ensure const-correctness of argument pointers: int const* cannot be converted to void*, but void const*.

Solution 3 - C++

Types can be the result of templates; a template might state const T, and be instantiated with T as void.

The linked answer is misled, or rather, limited in view in that it regards the special case of a non-template type, and even then const void might be meaningless, but it is valid code.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAjayView Question on Stackoverflow
Solution 1 - C++Benjamin LindleyView Answer on Stackoverflow
Solution 2 - C++ColumboView Answer on Stackoverflow
Solution 3 - C++DevSolarView Answer on Stackoverflow