1

我可以声明foo(const T& var)以便我知道 var 不会被更改。

指针的等效格式是foo(const T* var)

在过去,我尝试过那些与iterator/const_iterator激怒我相关的错误,我只是倾向于使用(T* var)而不考虑 constness。

是否有一个好的文档来声明强制指针指向的内容不会改变的函数?

4

2 回答 2

7

您所拥有的已经是一个禁止指针内容更改的指针。您可以通过使用“向后阅读”规则看到这一点:

const T* var     <===== left to right from this read

倒着读:

var是一个指向T常量的指针

这不同于

T* const var

内容如下:

var是一个指向 a 的常量指针T

这里的区别在于常数是var,而不是T; 这意味着您可以T通过取消引用来更改,var但您不能更改var指向的内容。

当然,您可以同时拥有以上两者:

const T* const var
于 2012-07-06T09:33:00.193 回答
0

(来自2个简单的变量初始化问题

一个非常好的经验法则const

从右到左阅读声明。

(参见 Vandevoorde/Josutiss “C++ 模板:完整指南”)

例如:

int const x; // x is a constant int
const int x; // x is an int which is const

// easy. the rule becomes really useful in the following:
int const * const p; // p is const-pointer to const-int
int const &p;        // p is a reference to const-int
int * const * p;     // p is a pointer to const-pointer to int.

自从我遵循这条经验法则以来,我再也没有误解过这样的声明。

(: sisab retcarahc-rep a no ton ,sisab nekot-rep a no tfel-ot-thgir naem I hguohT :tidE

同样,您可以将函数签名写入此规则:

void foo (int const * const p)

现在,p是一个指向 const-int 的 const 指针。这意味着在函数体内,你不能让p指向别的东西,即你不能改变指针,也不能改变它所指向的东西。

p 作为一个常量指针是真正只与你的函数体相关的信息,你应该从头文件中省略这些信息:

// foo.h
void foo (int const *p);

然后

// foo.cc
void foo (int const * const p) {
    // Here, the const serves you as the implementor as an additional
    // safety gear.
}
于 2012-07-06T12:10:00.833 回答