Alex Rivera | Logout

Why is it impossible to have a reference-to-void?

Asked 2009-01-19T15:09:15.913
56

Why is it impossible to have a reference to void? The only thing I found in the C++ Standard is this line, at 8.3.2.1

A declarator that specifies the type "reference to cv void" is ill-formed.

Why is it that way? Why can't I write a "generic" function that accept a void&?

Just to be clear, I have no useful application in mind where using a reference-to-void could be better than using templates, but I'm just curious about the rationale for forbidding this construct.


To clarify a little, I understand that using a reference-to-void "as is" would be as meaningless as dereferencing a pointer-to-void. However, I could cast it to a reference-to-sometype in order to use it, couldn't I? In fact, I don't see why the following snippet can work...

void foo(void *data)
{
    int *i = reinterpret_cast<int*>(data);
    // do something with i
}

...while this one cannot:

void foo(void &data)
{
    int &i = reinterpret_cast<int&>(data);
    // do something with i
}
Edit
Report

1 Answer

0

If they were, they would be semantically non-differentiated from pointers, and would amount to syntactic sugar. A reference says, "I refer to something that is of this type." Allowing void or null reference would weaken that difference from pointers.

Granted, it's still possible for a reference to refer to an object that doesn't exist anymore, but that is an exception.

answered 2009-01-19T18:39:07.380

Your Answer