First, I have a set
std::set<int*> my_set;
Then, I have a function for checking whether a specific int pointer p
exists in my_set
, that does nothing more than returning true
if it the pointer exists in it, and false
otherwise.
Since the function does not modify the referenced int
, it is natural to take the pointer as a const int*
, that is
bool exists_in_my_set(const int* p)
{
return my_set.find(p) != my_set.end();
}
However, when I try to compile the code, I get the following error:
error: invalid conversion from 'const int*' to 'std::set<int*>::key_type {aka int*}' [-fpermissive]
In other words, the compiler tries to cast the const int*
to an int*
when I call find
.
Anyway, my question is: How can I find p
in my_set
, or at least find out whether p
exists in my_set
or not, using the existing definitions of p
and my_set
?
int *const is a constant pointer to integer This means that the variable being declared is a constant pointer pointing to an integer. Effectively, this implies that the pointer shouldn't point to some other address.
const int * And int const * are the same. const int * const And int const * const are the same. If you ever face confusion in reading such symbols, remember the Spiral rule: Start from the name of the variable and move clockwise to the next pointer or type.
int const function(parameters) The const is redundant. Declaring a simple type such as int as a const return value is not useful, although it may help to make the code more self-documenting. If the return type is a reference or pointer however then the story changes.
Pointers with a constant memory address are declared by including the const after the *. Because the address is const, the pointer must be assigned a value immediately.
You can use const_cast<>
to remove constness from the parameter before searching the set<>
:
return my_set.find(const_cast<int*>(p)) != my_set.end();
There's no particular technical reason the library couldn't support allow what you expect, but on the other hand - forcing an explicit const_cast
is documenting that an operation involving a const
pointer is somehow getting non-const
access through the set
... arguably nice documentation that something a little unusual is up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With