c++ - Casting a pointer by reference -


i came across don't understand well. let's suppose want pass character pointer function takes reference void pointer.

void dostuff(void*& buffer) {   // } 

i :

int main() {   unsigned char* buffer = 0;   void* b = reinterpret_cast<void *>(buffer);   dostuff(b);   return 0; } 

why not possible directly pass reinterpret_cast function?

int main() {   unsigned char* buffer = 0   // generate compilation error.   dostuff(reinterpret_cast<void *>(buffer));   // fine.   dostuff(reinterpret_cast<void *&>(buffer));   return 0; } 

there must reason behind behavior don't see it.

in first example, you're passing pointer variable b. works.

in second example, first reinterpret_cast returns pointer (by value), doesn't match reference function should get, while second returns said reference.

as example show how references work, @ these 2 functions,

void dosomething( unsigned char *ptr ); void dosomethingref( unsigned char *&ptr ); 

say have pointer,

unsigned char *a; 

both functions called same way,

dosomething( ); // passing pointer value dosomethingref( );// passing pointer reference 

though may you're passing value, function takes reference passed reference.

a reference similar pointer has initialized left value , can't null.


having said that, there better alternatives using void* , void*&. void* makes code harder read , easier shoot in foot (if making use these strange casts).

as said in comments, use template , not bother void casting.

template< class t > void dostuff( t *&buffer ) {     ... } 

or,

template< class t > t* dostuff( t* buffer ) {     ... } 

edit: on side note, second example missing semicolon,

unsigned char* buffer = 0; // right here 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -