开发者

Question about const pointer in C++?

I cannot explain myself the following code:

   double d = 100;

    double const d1 = 30;

    double* co开发者_如何学运维nst p = &d; // Line 1
    double* const p1 = &d1; // Line 2

In the above code, Line 1 is ok, but Line 2 produces the error:

"error C2440: 'initializing' : cannot convert from 'const double *__w64 ' to 'double *const '"

Can anyone elaborate on that, please? (I am using VS C++ 2005, running on Win XP SP3)


The type double* const is a const pointer to a non-const double. If you want a pointer to a const double, you have to use double const* (or double const* const if you want a const pointer to a const double).

In C++, with a simple pointer to a double, you the const-ness of both the pointer itself (ie, can you make it point at another location) and the const-ness of the value (can you change the value through the pointer) can be configured independently. This gives you four very similar, but incompatibles types:

double const* const p1; // Const pointer to const double
                        //  . you can't have the pointer point to another address
                        //  . you can't mutate the value through the pointer

double const* p2;       // Non-const pointer to const double
                        //  . you can have the pointer point to another address
                        //  . you can't mutate the value through the pointer

double* const p3;       // Const pointer to double
                        //  . you can't have the pointer point to another address
                        //  . you can mutate the value through the pointer

double* p4;             // Non-const pointer to non-const double
                        //  . you can have the pointer point to another address
                        //  . you can mutate the value through the pointer


double * const p1 is declaring a const pointer to a non-const double, i.e. the pointer can change (i.e. it can be re-pointed), but not the thing that it's pointing to. But d1 is const.

Did you mean:

const double* p = &d; // Line 1
const double* p1 = &d1; // Line 2

?

[See also this question from the C++ FAQ.]


It is easier if you read declarations right to left:

double const *       p; // pointer to const double
const double *       p; // pointer to const double
double       * const p; // const pointer to double
double const * const p; // const pointer to const double


You may understand the code easily in the following manner.

double const d1 = 30;
double* const p1 = &d1;

Here in line 2, the problem is we are assigning a const value d1 to non-const value which can be changed in future.

It would be easier if we understand the data type of right side value to the left side value.

In our case, right side datatype can be treated as pointer to const double where as left side is a pointer to double, which contradicts and a compilor error is thrown.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜