这里以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-const
	int a			= 5;
	int *p1			= &a; //non-const pointer, non-const data
	const int *p2		= &a; //non-const pointer, const data, value pointed to by p2 can’t change
	int * const p3		= &a; //const pointer, non-const data, p3 cannot point to a different location
	const int * const p4	= &a; //const pointer, const data, both the pointer and the value pointed to cannot change
	int 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 constant

	char 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 constant
	s++;         // 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 *ptr
	int 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 ptr
	int 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 6

	const 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 value

	const 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 identifier
	fprintf(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" tag
		return 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(); // Ok
	int x = constC.Get();    // Ok: Get() is const

	nonConstC.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;
}

GitHubhttps://github.com/fengbingchun/Messy_Test

C++中const指针用法汇总的更多相关文章

  1. Leetcode刷题之矩阵中的指针用法

    矩阵中的指针用法 1 快慢指针 ​ Leetcode27移除元素 给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度.不要使用额外的数组 ...

  2. C/C++中const的用法 分类: C/C++ 2015-07-05 00:43 85人阅读 评论(0) 收藏

    const是C语言的关键字,经C++进行扩充,变得功能强大,用法复杂.const用于定义一个常变量(只读变量),当const与指针,引用,函数等结合起来使用时,情况会变得复杂的多.下面将从五个方面总结 ...

  3. C++中const关键字用法

    为什么使用const?采用符号常量写出的代码更容易维护:指针常常是边读边移动,而不是边写边移动:许多函数参数是只读不写的.const最常见用途是作为数组的界和switch分情况标号(也可以用枚举符代替 ...

  4. C++中cin的用法汇总

    cin可以用于接收输入,最常见的是从控制台接收.在刚学习C++的时候经常会用cin来接收数据,这里想要系统的总结一下cin的用法,保证不灌水. C++中的cin是一个 istream对象,从标准输入中 ...

  5. Vue3中插槽(slot)用法汇总

    Vue中的插槽相信使用过Vue的小伙伴或多或少的都用过,但是你是否了解它全部用法呢?本篇文章就为大家带来Vue3中插槽的全部用法来帮助大家查漏补缺. 什么是插槽 简单来说就是子组件中的提供给父组件使用 ...

  6. 如何牢记C/C++中const的用法?

    (下面以 typename 表示C/C++内某一类型 我常常会搞混 const 放在 typename* 的前面和后面的区别,今天特地查看了它们两个各自的含义,总结了一下: const typenam ...

  7. js中typeof的用法汇总[转载]

    http://www.jb51.net/article/43187.htm JavaScript中的typeof其实非常复杂,它可以用来做很多事情,但同时也有很多怪异的表现.本文列举出了它的多个用法, ...

  8. C++中const的用法

    1.const修饰普通变量和指针 (1).const修饰普通变量 其写法有2种:a.const type value;   b.type const value; 这两种写法本质上是一样的.其含义是: ...

  9. 基于c语言中调试工具的用法汇总(不包含gdb)【转】

    转自:http://www.jb51.net/article/36829.htm 是不是只有编译的时候才知道程序写了错误?有没有在未编译的时候就让机器帮你检查错误的工具呢? 答案是:有!! splin ...

随机推荐

  1. python16_day03【集合、编码、函数、递归、内置函数】

    一.集合 集合是一个无序的,不重复的数据组合,它的主要作用如下: 去重,把一个列表变成集合,就自动去重了 关系测试,测试两组数据之前的交集.差集.并集等关系 #创建: s = {3,5,9,10} # ...

  2. MySQL ——索引原理与慢查询优化(Day45)

    阅读目录 一 介绍 二 索引的原理 三 索引的数据结构 三 MySQL索引管理 四 测试索引 五 正确使用索引 六 查询优化神器-explain 七 慢查询优化的基本步骤 八 慢日志管理 ====== ...

  3. 编程语言的介绍(Day2)

    1.什么是编程,为什么要编程? 编程==编写程序(写代码) 2.编程语言有哪些 机器语言 优点是最底层,速度最快,缺点是最复杂,开发效率最低 汇编语言 优点是比较底层,速度最快,缺点是复杂,开发效率最 ...

  4. centos6.5系统python2.6升级到python3.6

    1.安装必备的工具 wget:yum install wget gcc:yum install gcc zlib zlib-devel: yum install zlib zlib-devel -y ...

  5. Why GraphQL is Taking Over APIs

    A few years ago, I managed a team at DocuSign that was tasked with re-writing the main DocuSign web ...

  6. Java并发之Semaphore的使用

    Java并发之Semaphore的使用 一.简介 今天突然发现,看着自己喜欢的球队发挥如此的棒,然后写着博客,这种感觉很爽.现在是半场时间,就趁着这个时间的空隙,说说Java并发包中另外一个重量级的类 ...

  7. netty4----netty5的客户端和服务端

    服务端: package com.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; ...

  8. Building an FTP Test Plan

    参考:http://jmeter.apache.org/usermanual/build-ftp-test-plan.html 1.创建一个线程组 2.线程组--->添加--->配置元件- ...

  9. 利用同步网盘搭建个人或团队SVN服务器

    这篇文章是以前写的,现在强烈推荐两个站.1.http://git.oschina.com 2.http://www.coding.net. 推荐理由:1.可创建私有项目.2.免费稳定.3.VS2013 ...

  10. Tomcat 启动内存修改

    内存修改文件 Windows 文件 /bin/catalina.bat Linux 文件 /bin/catalina.sh 方法一 # 设置参数 JAVA_OPTS='-Xms[初始化内存大小] -X ...