c++ - Why must an argument ever be cast to const? -


my understanding const in argument declaration represents function being declared not change const value. why ever place demand on constness of argument passed caller?

the defining code:

void func(const foo**);  main() {   foo* fooptr;   func(&fooptr); } 

visual studio 2012 compiler yields:

> error c2664: 'func' : cannot convert parameter 1 'foo**' 'const foo**' > conversion loses qualifiers 

but following works:

main() {   foo* fooptr;   func(const_cast<const foo**>(&fooptr)); } 

what underlying theory?

if conversion allowed, used circumvent const-correctness:

const foo const_foo;  void evil(const foo** p) {     *p = &const_foo; // *p 'const foo*', assignment allowed }  int main() {     foo* p;     evil(&p);     // modifies p point const_foo     p->modify();  // boom! modifying constant object } 

you can convert const foo* const*; doesn't allow change foo* point else, can't break const-correctness. better using dodgy cast , hoping best; although should ask why you're not passing pointer value, if don't want change it.


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -