MarkXLII MarkXLII - 4 months ago 36
C++ Question

Error: passing ‘const string {aka const std::__cxx11::basic_string<char>}’ as ‘this’ argument

I have the following code for dealing with doubles:

static bool
double_param(const char ** p, double * ptr_val)
{
char *end;
errno = 0;
double v = strtod(*p, &end);
if (*p == end || errno) return false;
*p = end;
*ptr_val = v;
return true;
}


This code is used to check whether passed double parameter is invalid like so:

if (!double_param(&p, &b1)) //p is pointer and b1 is parameter.
//throw error;


And, I need to write an equivalent code for dealing with string of 3 characters long. I've gotten this on my own:

static bool
string_param(const char ** p, const string * ptr_val)
{
char *end;
errno = 0;
int v = strtol(*p, &end, 10);
if (*p == end || errno) return false;
*p = end;
*ptr_val = v;
return true;
}


but I get the following compile error:

error: passing ‘const string {aka const std::__cxx11::basic_string<char>}’ as ‘this’ argument discards qualifiers [-fpermissive]
(*ptr_val) = v;
^


Any suggestions are appreciated to get around this error. Also, please point out the mistake in my code and explain a little so that I can understand better and learn. Thanks in advance.

Answer

*ptr_val is a pointer to a const string. You are trying to change the value of a const string, which of course you cannot do.

You can instead do a const pointer like this: string * const ptr_val

This means that you can change the value of the data the pointer is pointing to, but you cannot change what the pointer points to.