D
Dom Bannon
I have a simple function which scans through a C-string. This function
doesn't modify the string, so I'd like to contract with the caller
that I won't change anything. However, this seems to be difficult if I
also need to return to the caller a location in the string, *and* the
caller doesn't want the contract.
For example:
---------------------------
/**
* @param p1 String to scan
* @param p2 A ptr in the string is returned here on success
* @return True on success, else false
*/
bool foo(const char *p1, const char* &p2) {
const char *cptr = p1;
++cptr;
p2 = cptr;
return true;
}
int main() {
// I don't want the const contract with 'foo': I need
// to change something at bar2
char *bar1, *bar2;
foo(bar1, bar2);
return 0;
}
---------------------------
However, this (complete program) doesn't compile. The compiler doesn't
require bar1 to be a 'const char*', but it *does* require bar2 to be a
'const char*'.
So, is there a good way to write my function so that the caller can
ignore the const contract if necessary? Or does caller have to
explicitly cast away the constness?
Thanks -
Dom
doesn't modify the string, so I'd like to contract with the caller
that I won't change anything. However, this seems to be difficult if I
also need to return to the caller a location in the string, *and* the
caller doesn't want the contract.
For example:
---------------------------
/**
* @param p1 String to scan
* @param p2 A ptr in the string is returned here on success
* @return True on success, else false
*/
bool foo(const char *p1, const char* &p2) {
const char *cptr = p1;
++cptr;
p2 = cptr;
return true;
}
int main() {
// I don't want the const contract with 'foo': I need
// to change something at bar2
char *bar1, *bar2;
foo(bar1, bar2);
return 0;
}
---------------------------
However, this (complete program) doesn't compile. The compiler doesn't
require bar1 to be a 'const char*', but it *does* require bar2 to be a
'const char*'.
So, is there a good way to write my function so that the caller can
ignore the const contract if necessary? Or does caller have to
explicitly cast away the constness?
Thanks -
Dom