Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert "pointer to pointer type" to const?

With the following code

void TestF(const double ** testv){;}
void callTest(){
    double** test;
    TestF(test);
}

I get this:

'TestF' : cannot convert parameter 1 from 'double **' to 'const double **'

I cannot understand why. Why test cannot be silently casted to const double**? Why should I do it explicitly? I know that

TestF(const_cast<const double**>(test)) 

makes my code correct, but I feel this should be unnecessary.

Are there some key concepts about const that I'm missing?

like image 668
jimifiki Avatar asked Nov 11 '13 15:11

jimifiki


People also ask

How do you declare a pointer to const?

We declare a constant pointer. First, we assign the address of variable 'a' to the pointer 'ptr'. Then, we assign the address of variable 'b' to the pointer 'ptr'. Lastly, we try to print the value of the variable pointed by the 'ptr'.

Can a pointer be const?

A pointer to a const value (sometimes called a pointer to const for short) is a (non-const) pointer that points to a constant value. In the above example, ptr points to a const int . Because the data type being pointed to is const, the value being pointed to can't be changed. We can also make a pointer itself constant.

What is difference between constant pointer and pointer to constant?

In the constant pointers to constants, the data pointed to by the pointer is constant and cannot be changed. The pointer itself is constant and cannot change and point somewhere else.

Can you return a const pointer?

Returning a pointer to const makes a lot of sense, but returning a const pointer (you cannot modify) usually adds no value (although some say it can prevent user errors or add compiler optimisation).


1 Answers

The language allows implicit conversion from double ** to const double *const *, but not to const double **. The conversion you attempt would implicitly violate the rules of const correctness, even though it is not immediately obvious.

The example in the [de-facto standard] C++ FAQ illustrates the issue

https://isocpp.org/wiki/faq/const-correctness#constptrptr-conversion

Basically, the rule is: once you add const at some level of indirection, you have to add const to all levels of indirection all the way to the right. For example, int ***** cannot be implicitly converted to int **const ***, but it can be implicitly converted to int **const *const *const *

like image 126
AnT Avatar answered Oct 06 '22 00:10

AnT