Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is const void?

Tags:

c++

c++11

c++14

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?

like image 229
Ajay Avatar asked Jun 17 '16 12:06

Ajay


People also ask

Can a void function be const?

void* is normally used as a way to pass non-specific pointers around (e.g. with memcpy() ). If you want to pass a const char* to such a function then you cannot use void* or you lose the fact that the thing it points to is constant and cannot be altered.

What is void * C++?

void (C++) If a pointer's type is void* , the pointer can point to any variable that's not declared with the const or volatile keyword. A void* pointer can't be dereferenced unless it's cast to another type. A void* pointer can be converted into any other type of data pointer.

What is const modifier?

Const means simply, as you described, that the value is read-only. constant expression, on the other hand, means the value is known compile time and is a compile-time constant. The semantics of const in C are always of the first type.

What is the purpose of a const?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.


1 Answers

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 
like image 84
Benjamin Lindley Avatar answered Oct 12 '22 02:10

Benjamin Lindley