Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert void* to const void**

Tags:

c++

In CPP I use a C library, one of the method needs a const void ** as parameter.

In my class I have a property whose type is void *.

I tried to call the function by doing function(&my_property) but the compiler complained that it could not convert a void ** to a const void **.

To fix this issue I used a const cast and did function(const_cast<const void *>(&my_property)).

I try to avoid casting as much as possible and I would like to know if there is a "clean" way to do that without using a const cast.

like image 534
f222 Avatar asked Jul 24 '26 06:07

f222


2 Answers

Proper solution would be to turn my_property into const void*. Otherwise you might break a contract of function.

like image 136
Konstantin Stupnik Avatar answered Jul 25 '26 21:07

Konstantin Stupnik


Replicating your situation in a simple manner, let's say you have this code:

void function(const void **p)
{
    //...
}

int main()
{
    void *my_property;
    function(&my_property);
}

Using const_cast is safe, I don't think it's all that unclean, but you have alternatives, the best of wich would be to turn my_property into a const void*, suspecting that may not be an option, you may just use a const void* pointer to wich you would assign the original void*:

void *my_property;
const void *pp = my_property;
function(&pp);

The conversion is still there, but it's implicit.

As Quentin very accurately pointed out, this does not make a lot of sense, unless it's just to shut up the compiler.

like image 27
anastaciu Avatar answered Jul 25 '26 19:07

anastaciu