1

I don't understand something here. In the following code I have defined an integer and a constant integer.

I can have a constant pointer (int* const) point to an integer. See the fourth line of code.

The same constant pointer (int* const) can not point to a constant integer. See the fifth line.

A constant pointer to a const (const int* const) can point to a constant integer. That's what I would expect.

However, the same (const int* const) pointer is allowed to point to a non constant integer. See the last line. Why or how is this possible?

int const constVar = 42;
int variable = 11;

int* const constPointer1 = &variable;
int* const constPointer2 = &constVar; // not allowed
const int* const constPointer3 = &constVar; // perfectly ok
const int* const constPointer4 = &variable; // also ok, but why?
4

5 回答 5

2
int const constVar = 42;  // this defines a top-level constant
int variable = 11;

int *const constPointer1 = &variable;

int *const constPointer2 = &constVar; // not allowed because you can change constant using it

const int *const constPointer3 = &constVar; // perfectly ok. here you can't change constVar by any mean. it is a low level constant.

const int *const constPointer4 = &variable; // also ok, because it says you can't change the value using this pointer . but you can change value like variable=15 .

*constPointer4=5; //you get error assignment of readonly location.because that pointer is constant and pointing to read only memory location.

于 2013-02-08T19:22:27.637 回答
1

const 的访问权限比非 const 少,这就是允许它的原因。您将无法通过指针更改“变量”,但这并不违反任何规则。

variable = 4; //ok
*constPointer4 = 4; //not ok because its const

在调用函数时,您经常使用这种“指向非 const 变量的 const 指针”情况。

void f(const int * const i)
{
    i=4; //not ok
}

f(&variable);
于 2013-02-08T19:19:04.980 回答
1

您始终可以决定不修改非常量变量。

const int* const constPointer4 = &variable;

只需解析定义:constPointer4 是一个指向 const int (即)的 const (即您不能再更改它所指向的内容)的指针variable。这意味着您不能通过 修改variable constPointer4即使您可以variable通过其他方式进行修改。

反过来(通过非常量指针访问 const 变量),您需要一个const_cast.

为什么指向 const 的指针有用?它允许您const在类中拥有成员函数,您可以向用户保证该成员函数不会修改对象。

于 2013-02-08T19:19:24.807 回答
0

指向 const 对象的指针不能用于修改该对象。别人能不能修改没关系;它只是不能通过那个指针来完成。

int i;               // modifiable
const int *cip = &i; // promises not to modify i
int *ip = &i;        // can be used to modify i

*cip = 3; // Error
*ip = 3;  // OK
于 2013-02-08T19:27:24.230 回答
0

第 4 行

int* const constPointer2 = &constVar;

此处不应允许,因为“int* const constPointer2”的 int* const 部分意味着指针是恒定的,然后当您继续将其分配给 &constVar

于 2013-02-08T19:32:24.483 回答