Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Ask your self first, how you would de-reference a void pointer? </p> <pre><code>void *p = /*something*/ ; cout &lt;&lt; *p &lt;&lt; endl; </code></pre> <p>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.</p> <p>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.</p> <p>To reference it you - the programmer - need to cast it to another type, then you can have a typed reference to it.</p> <p>Not sure if I explained this as well as I wanted to.</p> <p>Ruben, any thoughts?</p> <p><strong>EDIT:</strong> To answer your edit.</p> <p>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.</p> <pre><code>logger &lt;&lt; data; </code></pre> <p>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. </p> <pre><code>void* data = /* some assignment */; logger &lt;&lt; *data; // compiler error. </code></pre> <p>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 &amp;data, except that because it's a reference <em>it's implicitly dereferenced all the time</em>. The compiler won't let you dereference a void* on one operation, it's not going to let you dereference it constantly.</p> <pre><code>void&amp; data = /* some assignment *.; logger &lt;&lt; data; // means same as logger &lt;&lt; *data above </code></pre> <p>You can't do <strong>ANYTHING</strong> to data <strong>EXCEPT</strong> take it's address, and there's a perfectly good - and safe - method built into the languge to do that, i.e.</p> <pre><code>void* data; </code></pre> <p>Is this making any more sense?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload