是的,
void function(int* const ptr){
int i;
// ptr = &i wrong expression, will generate error ptr is constant;
i = *ptr; // will not error as ptr is read only
//*ptr=10; is correct
}
int main(){
int i=0;
int *ptr =&i;
function(ptr);
}
Run Code Online (Sandbox Code Playgroud)
在void function(int* const ptr)ptr 中是常量,但 ptr 指向的不是常量,因此*ptr=10是正确的表达式!
void Foo( int * ptr,
int const * ptrToConst,
int * const constPtr,
int const * const constPtrToConst )
{
*ptr = 0; // OK: modifies the "pointee" data
ptr = 0; // OK: modifies the pointer
*ptrToConst = 0; // Error! Cannot modify the "pointee" data
ptrToConst = 0; // OK: modifies the pointer
*constPtr = 0; // OK: modifies the "pointee" data
constPtr = 0; // Error! Cannot modify the pointer
*constPtrToConst = 0; // Error! Cannot modify the "pointee" data
constPtrToConst = 0; // Error! Cannot modify the pointer
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 const
void foo(const char * pc)
这里pc是指向const char的指针,通过使用pc你无法编辑内容.
但它并不保证您无法更改内容,因为通过创建指向相同内容的另一个指针,您可以修改内容.
所以,这取决于你,你将如何实现它.
我必须确保该功能不会编辑内容
除非该函数采用const参数,否则您唯一能做的就是显式向其传递数据的副本,可能是使用memcpy.
| 归档时间: |
|
| 查看次数: |
3978 次 |
| 最近记录: |