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

后端 未结 10 1011
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-23 19:32

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 th

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-23 20:38

    Ask your self first, how you would de-reference a void pointer?

    void *p = /*something*/ ;
    cout << *p << endl;
    

    The above code is meaningless, one of the reasons we have void is so we can say "I need to do some generic pointer work here, and I neither know nor care what I'm pointing to". By definition, the compiler doesn't know what a void * points to, therefore it can't dereference it. You can - by casting - but the compiler can't.

    A reference to a void sufferes from the same problem, by definition the data pointed to doesn't have a type, therefore it can't be referenced in any meaningful way.

    To reference it you - the programmer - need to cast it to another type, then you can have a typed reference to it.

    Not sure if I explained this as well as I wanted to.

    Ruben, any thoughts?

    EDIT: To answer your edit.

    Take the first function, where you pass void* data. data is a perfectly valid item, you can compute with it, or if you've some logging implemented, you can log it.

    logger << data;
    

    and you'll get the address data points to. If you try to dereference data, the compiler will give you an error (don't have C++ compiler handy at moment, so not sure of the actual error). e.g.

    void* data = /* some assignment */;
    logger << *data; // compiler error.
    

    Now, the compiler won't let you dereference a void* for any reason (it doesn't make sense), the same stands for a reference to void &data, except that because it's a reference it's implicitly dereferenced all the time. The compiler won't let you dereference a void* on one operation, it's not going to let you dereference it constantly.

    void& data = /* some assignment *.;
    logger << data; // means same as logger << *data above
    

    You can't do ANYTHING to data EXCEPT take it's address, and there's a perfectly good - and safe - method built into the languge to do that, i.e.

    void* data;
    

    Is this making any more sense?

提交回复
热议问题