【问题标题】:Use a const int* const pointer to point to an int使用 const int* const 指针指向 int
【发布时间】:2013-02-08 19:16:30
【问题描述】:

这里有什么我不明白的。在下面的代码中,我定义了一个整数和一个常量整数。

我可以让一个常量指针 (int* const) 指向一个整数。见第四行代码。

同一个常量指针(int* const)不能指向一个常量整数。见第五行。

指向 const (const int* const) 的常量指针可以指向一个常量整数。这就是我所期望的。

但是,允许相同的 (const int* const) 指针指向一个非常数整数。见最后一行。为什么或如何可能?

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?

【问题讨论】:

  • 您似乎对 const 关键字的含义有误解。 const int* 不是“我指向的 int 是 const”,而是“我不会用这个指针来改变我指向的 int”。您指向的 int 是否为 const 不会改变正在发生的事情。
  • 感谢您的所有回答和 cmets。就像比尔在他的评论中写的那样,我弄错了。 C++ 有时很难获得。

标签: c++ pointers constants


【解决方案1】:
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.

【讨论】:

    【解决方案2】:

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

    const int* const constPointer4 = &variable;
    

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

    反过来(通过非 const 指针访问 const 变量),您将需要 const_cast

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

    【讨论】:

      【解决方案3】:

      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);
      

      【讨论】:

        【解决方案4】:

        指向 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
        

        【讨论】:

          【解决方案5】:

          第 4 行

          int* const constPointer2 = &constVar;
          

          这里不应该允许,因为“int* const constPointer2”的int* const部分意味着指针是恒定的,然后当你继续将它分配给&constVar

          【讨论】:

            猜你喜欢
            • 2015-09-10
            • 1970-01-01
            • 2021-05-10
            • 2020-12-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多