c++ - const input vs non-const output -


i have function traverses tree of objects , not modify of objects in tree.

the function looks this:

static node* findmatchingnode(const node& root, const somefilterdata& d);  struct node {    node* left;    node* right; }; 

the function can return root or object in tree or nothing. it's obvious given declaration have perform const_cast somewhere, forbidden in cases.

is acceptable function guarantee constness , @ same time allow modify output?

edit. haven't stated clearly, function not modify of nodes in tree, doesn't create new node, it's pure function. i'd have const qualifier there tell function doesn't modify anything

edit. unspoken problem behind there no legal way express constness of input during function execution (and inside function) without enforcing output constness.

your code not const-correct, drops const. why have problem of "required" const cast. don't that:

static const node* findmatchingnode(const node& root, const somefilterdata& d); 

you may point out may want call function function does modify nodes, , wants non-const result. such, should new function totally different signature:

static node* findmatchingnode(node& root, const somefilterdata& d); 

you may point out these have identical bodies, , there's dry principle (dry = don't repeat = don't have copy-pasted code). yes, take shortcut here: const_cast. think it's ok in case, because it's only purpose shared code, , it's clear it's not violating const-correctness principles.

//this function not modify static node* findmatchingnode(node& root, const somefilterdata& d) {     return const_cast<node*>(findmatchingnode(const_cast<const node&>(root),d)); } 

loki asari suggests adding third private function findmatchingnodecommon() both versions of findmatchingnode() call. can away 1 less const_cast. if want go extreme can make findmatchingnodecommon() templated , const_casts go away. think it's not worth bother, they're valid opinions, worth mention.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -