这里以int类型为例,进行说明,在C++中const是类型修饰符:

int a; 定义一个普通的int类型变量a,可对此变量的值进行修改。

const int a = 3;与 int const a = 3; 这两条语句都是有效的code,并且是等价的,说明a是一个常量,不能对此常量的值进行修改。

const int* p =&a; 与 int const* p = &a; 这两条语句都是有效的code,但是它们不是等价的。其中const int* p = &a; 是平时经常使用的格式,声明一个指针,此指针指向的数据不能通过此指针被改变;int* const p = ∫ 声明一个指针,此指针不能被改变以指向别的东西。

const int *a; 这里const修饰的是int,而int定义的是一个整值,因此*a所指向的对象值不能通过*a来修改,但是可以重新给a来赋值,使其指向不同的对象;

int *const a; 这里const修饰的是a,a代表的是一个指针地址,因此不能赋给a其他的地址值,但可以修改a指向的值;

int const *a;和const int *a;的意义是相同的,它们两个的作用等价;

rules:

(1). A non-const pointer can be redirected to point to other addresses.

(2). A const pointer always points to the same address, and this address can not be changed.

(3). A pointer to a non-const value can change the value it is pointing to. These can not point to a const value.

(4). A pointer to a const value treats the value as const (even if it is not), and thus can not change the value it is pointing to.

以下是一些test code,详细信息可见相关的reference:

#include <iostream>
#include "const_pointer.hpp"int test_const_pointer_1()
{
{ // reference: https://stackoverflow.com/questions/3247285/const-int-int-constint a            = 5;int *p1            = &a; //non-const pointer, non-const dataconst int *p2     = &a; //non-const pointer, const data, value pointed to by p2 can’t changeint * const p3       = &a; //const pointer, non-const data, p3 cannot point to a different locationconst int * const p4 = &a; //const pointer, const data, both the pointer and the value pointed to cannot changeint const * const p5 = &a; // 与 const int * const p5等价
}{ // reference: https://stackoverflow.com/questions/162480/const-int-vs-int-const-as-function-parameter-in-c-and-c// read the declaration backwards (right-to-left):const int a1 = 1; // read as "a1 is an integer which is constant"int const a2 = 1; // read as "a2 is a constant integer"// a1 = 2; // Can't do because a1 is constant// a2 = 2; // Can't do because a2 is constantchar a = 'a';const char *s = &a; // read as "s is a pointer to a char that is constant"char const *y = &a; // 与 const char *y 等价char c;char *const t = &c; // read as "t is a constant pointer to a char"// *s = 'A'; // Can't do because the char is constants++;         // Can do because the pointer isn't constant*t = 'A';    // Can do because the char isn't constant// t++;      // Can't do because the pointer is constant// *y = 'A';y++;
}{ // reference: http://www.geeksforgeeks.org/const-qualifier-in-c/int i = 10;int j = 20;int *ptr = &i;        /* pointer to integer */printf("*ptr: %d\n", *ptr);/* pointer is pointing to another variable */ptr = &j;printf("*ptr: %d\n", *ptr);/* we can change value stored by pointer */*ptr = 100;printf("*ptr: %d\n", *ptr);
}{ // const int *ptr <==> int const *ptrint i = 10;int j = 20;const int *ptr = &i;    /* ptr is pointer to constant */printf("ptr: %d\n", *ptr);// *ptr = 100;        /* error: object pointed cannot be modified using the pointer ptr */ptr = &j;          /* valid */printf("ptr: %d\n", *ptr);
}{ // int * const ptrint i = 10;int j = 20;int *const ptr = &i;    /* constant pointer to integer */printf("ptr: %d\n", *ptr);*ptr = 100;    /* valid */printf("ptr: %d\n", *ptr);// ptr = &j;        /* error */
}{ // const int *const ptr;int i = 10;int j = 20;const int *const ptr = &i;        /* constant pointer to constant integer */printf("ptr: %d\n", *ptr);// ptr = &j;            /* error */// *ptr = 100;        /* error */
}{ // reference: http://www.learncpp.com/cpp-tutorial/610-pointers-and-const/int value = 5;int *ptr = &value;*ptr = 6; // change value to 6const int value2 = 5; // value is const// int *ptr2 = &value2; // compile error: cannot convert const int* to int*const int *ptr3 = &value2; // this is okay, ptr3 is pointing to a "const int"// *ptr3 = 6; // not allowed, we can't change a const valueconst int *ptr4 = &value; // ptr4 points to a "const int"fprintf(stderr, "*ptr4: %d\n", *ptr4);value = 7; // the value is non-const when accessed through a non-const identifierfprintf(stderr, "*ptr4: %d\n", *ptr4);
}return 0;
}//
// reference: https://en.wikipedia.org/wiki/Const_(computer_programming)
class C {int i;
public:int Get() const { // Note the "const" tagreturn i;}void Set(int j) { // Note the lack of "const"i = j;}
};static void Foo_1(C& nonConstC, const C& constC)
{int y = nonConstC.Get(); // Okint x = constC.Get();    // Ok: Get() is constnonConstC.Set(10); // Ok: nonConstC is modifiable// constC.Set(10);    // Error! Set() is a non-const method and constC is a const-qualified object
}class MyArray {int data[100];
public:int &       Get(int i)       { return data[i]; }int const & Get(int i) const { return data[i]; }
};static void Foo_2(MyArray & array, MyArray const & constArray) {// Get a reference to an array element// and modify its referenced value.array.Get(5) = 42; // OK! (Calls: int & MyArray::Get(int))// constArray.Get(5) = 42; // Error! (Calls: int const & MyArray::Get(int) const)
}typedef struct S_ {int val;int *ptr;
} S;void Foo_3(const S & s)
{int i = 42;// s.val = i;   // Error: s is const, so val is a const int// s.ptr = &i;  // Error: s is const, so ptr is a const pointer to int// *s.ptr = i;  // OK: the data pointed to by ptr is always mutable,// even though this is sometimes not desirable
}int test_const_pointer_2()
{C a, b;Foo_1(a, b);MyArray x, y;Foo_2(x, y);S s;Foo_3(s);return 0;
}

GitHub: https://github.com/fengbingchun/Messy_Test

C++中const指针用法汇总相关推荐

  1. C++中const关键字用法详解及实例和源码下载(一)

    最近在学习C++基础部分,看了两天书,已经看过了一遍,半知半解,回过头来重新看第二遍,深入了解一下C++的基础知识.现在读到了const关键字的用法,书上面讲解的时候并没有给出完整的实例,只是理论的讲 ...

  2. C++ 中const的用法,特别是用在函数前面与后面的区别!

    原文链接:https://www.cnblogs.com/doker/p/11051175.html 目录 第一:const修饰函数的参数 第二:用const修饰函数的返回值 第三:const 成员函 ...

  3. C++中const指针

    如何区分常量指针和指向常量的指针呢? 一个简单的方法:从右向左读. 例: const int p; // p是一个int型常量 这个很简单 const int *p; // p是一个指针,指向int型 ...

  4. const指针用法总结

    1.const限定符 const限定符可以把一个对象转换成一个常变量,常量在定义后就不能被修改,因此定义时必修初始化. const int bufSize = 512;//OK bufSize = 0 ...

  5. 某内存池中的指针用法

    内存池实现有许多种,各有不同的优缺点. 这里不是主要说内存池,只是觉得这个内存池中的指针用得很飘逸! template <class T,int AllocSize = 50> class ...

  6. C#中DllImport使用法汇总

    (转) 最近使用DllImport,从网上百度后发现,大部分内容都是相同,又从MSDN中搜集下,现将内容汇总,与大家分享. 大家在实际工作学习C#的时候,可能会问:为什么我们要为一些已经存在的功能(比 ...

  7. C++/C++11中std::string用法汇总

    C++/C++11中std::string是个模板类,它是一个标准库.使用string类型必须首先包含<string>头文件.作为标准库的一部分,string定义在命名空间std中. st ...

  8. C++中const的用法

    参考:https://www.cnblogs.com/xudong-bupt/p/3509567.html C++中的const C++ const 允许指定一个语义约束,编译器会强制实施这个约束,允 ...

  9. C/C++中static关键字用法汇总

    1. 函数内static局部变量:变量在程序初始化时被分配,直到程序退出前才被释放,也就是static是按照程序的生命周期来分配释放变量的,而不是变量自己的生命周期.多次调用,仅需一次初始化. 2. ...

最新文章

  1. 小程序无限层级路由方案
  2. Starting MySQL... ERROR! The server quit without updating PID file 问题解决
  3. python语言翻译-教你用Python抓取百度翻译
  4. 【Matlab】如何提取矩阵中特定位置的元素?
  5. oracle权限培训,Java培训-ORACLE数据库学习【2】用户权限
  6. Asp.Net Core Web Api图片上传(一)集成MongoDB存储实例教程
  7. 接入广域网技术——NAT内、外部网络地址转换
  8. 关于Mysql的错误:No query specified
  9. 华为P50或将全面搭载鸿蒙OS上市:明年一季度见
  10. Java的native方法返回数组return Array(C语言)
  11. Uncaught SyntaxError: Unexpected token ‘var‘
  12. php 多个箭头,php连续的两个箭头-〉是什么意思??
  13. 盈建科中地震波_[GMS][地震波][选波]YJK地震波反应谱分析与地震波选取
  14. document.getElementsByClassName的理想实现(@司徒正美 大神)
  15. 如何修改图像尺寸?教你两招轻松修改图像宽高像素
  16. 解析MOS管电流方向反及其体二极管能过多大电流问题
  17. CORTEX-A系列处理器
  18. pytorch转onnx报错的可能原因traced region did not have observable data dependence
  19. Windows 11 21H2正式版镜像
  20. mybatis中的动态sql

热门文章

  1. Linux那些事儿 之 戏说USB(33)字符串描述符
  2. 深度学习--TensorFlow(6)神经网络 -- 拟合线性函数非线性函数
  3. 【面向对象编程】(1) 类实例化的基本方法
  4. 【机器学习入门】(2) 朴素贝叶斯算法:原理、实例应用(文档分类预测)附python完整代码及数据集
  5. wpf 多线程处理同步数据_一文带你理解多线程的实际意义和优势
  6. QT 烦人的parent该如何理解
  7. Udacity机器人软件工程师课程笔记(十四)-运动学-正向运动学和反向运动学(其一)
  8. 业余快速学习虚幻引擎教程
  9. Zookeeper ZAB协议原理浅析
  10. 线程互斥和同步-- 互斥锁