const correctness problem

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
 
D

Dom Bannon

On Sun, 02 May 2010 08:51:00 -0400, Victor Bazarov
The simplest way around this, as I see it is to actually return the
index instead of the pointer. Another possibility - to overload the
function (have two of them), and have two different argument types:

Many thanks. I've gone for your first option, which also lets me get
rid of the boolean return value.

-Dom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top