Re: Reference to void
Salt_Peter wrote:
Is the following code valid?
int i = 5;
void* pv = &i;
void& rv = *pv; // Error here on VC 2005
If not, why isn't it valid?
Its not valid for the same reasons that the following is invalid:
void v = 5;
That is to say: a reference is an object and a valid object.
The same can't be said of a pointer, or any pointer.
Let's make the following assumption: every type is implicitly derived
from void. Many C++ programmers can accept that.
Then, is it impossible for us to think of void defined in the following
way:
class void
{
void(); // disabled
void(const void&); // disabled
template <typename T> void(T); // disabled
template <typename T> void operator=(T); // disabled
};
As you can see, we can easisly move from the "there can't be an object
of type void" thinking to the "we can't construct an object of type
void" thinking. The second form of thinking would allow us to have
references to void.
"So, what is this good for?" you might ask. You can't access any
methods to void, you can't call any operator. Still you should be able
to take it's address, and transform it to a pointer like this:
pv = &rv;
The only thing to do is impose that we cannot take the reference to a
void function result. Example:
// This shouldn't be allowed
void f() {}
void& result = f();
I think this constraint is less restrictive than the one we have now
that doesn't allows references to void.
Consider:
int i = 5;
What exactly is i ?
Is it not an alias to what would otherwise have been an anonymous
variable in memory?
Granted a reference is not the same beast, but it does serve the same
purpose.
Ideed, i can be considered a reference to an anonymous variable in
memory. But if you disable the creation of void object, there won't be
any void objects in memory. This means that you can have void
references, but this refenreces must point to variables of types more
specific than void. Of course, we consider here that every other type
is derived from void.
Is there something that I'm missing here?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]