c++c++11c++14voidconst-correctness

What is const void, and is it a valid return type?


The description of std::is_void 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 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?


Solution

  • 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