c/c++ const 关键字详解

int32位 posted @ Nov 06, 2013 06:21:33 PM in c/cpp , 2763 阅读
转载请注明:http://krystism.is-programmer.com/若有错误,请多多指正,谢谢!

首先讲讲c语言中const关键字的作用,很多书把const修饰的关键字叫做常量,但我认为还是叫做只读变量恰当点,毕竟它和真正的右值常量还是有区别的,除了只读(即只能定义时初始化,其他任何时候不能再修改)这个限制外,和普通变量没有什么区别。

基本使用方法,就是在变量声明的加上const修饰即可。如const int N = 0;即声明了一个只读变量N。这个N是不允许修改的。

关键在于涉及指针时需要弄清楚const修饰的是指针本身还是修饰指针指向的对象,这点很重要!

可以这样简单记忆,如果const在 * 前面则const修饰的是指针指向的对象,即指向的对象是只读的。如果const 在 *后面则修饰的是指针本身,即该指针变量不可指向其他对象,而指向的对象并不受const约束。如

	int x = 5, y = 6;
	const int *p = &x;
	int * const q = &x;
	// q = &y;
	// *p = 6;
	p = &y;
	*q = 7;

p指针不能修改指向对象的值(注意:只能说不能通过p来修改所指向对象的值,不能说指向的内容不能修改,完全可以通过其他方式修改其值,比如q指针),而q指针可以修改指向对象的值,但本身是一个只读变量,即不能再指向其他对象。另外,注意一点的是,const变量必须在声明时初始化,这和java中的final修饰符不同,final可以声明不进行初始化,可以在任何时候进行初始化。

c++的引用类型也基本类似,看 & 位置决定const修饰的内容。另外注意以下代码:

typedef int* Pointer;
int x = 5;
const Pointer p =  &x;

很容易把const Pointer p = &x, 展开为 const int *p = &x,引起错误! 注意typedef并不是简单的展开,它和宏有本质的区别。上面定义的p应该相对于int * const p = &x; 即p本身是可读变量,而不是其指向的对象不可修改。

const修饰符有什么作用,也许第一反应就是声明一个常量(为什么要声明常量?与宏#define的区别?)。其实更确切地说,const修饰符的功能是为了保护数据安全。

这在函数传参中更容易理解,假如我有一个char *s 字符串, 我要一个查找某个字符的位置的函数find,返回第一次出现该字符的索引,但我不希望由于传入参数后意外的被修改了原来的字符串,关键是这个函数还不一定是我自己写的,有可能是其他人写的。我们可以声明一个函数为 int find(const char *s)来达到这样的目的。 这样我就不用担心我的字符串被恶意修改了。因此:只要是不需要修改原来的内容,则尽量声明为const参数,减少出错率。比如在写qsort的cmp函数时,应该写成int cmp(const void *a, const void *b),因为不希望在比较的时候就把原来的值篡改了。不过一般情况下,const只对指针或者引用参数有效,int foo(const int n)纯属胡闹,因此该函数是传值,每次调用函数时,都会重新创建该函数所有的形参,此时所传递的实参将会初始化对应的形参,普通的非引用类型的参数通过复制对应的实参实现初始化,函数并没有访问调用所传递的实参本身,因此不会修改实参的值,而只是操作实参的一个副本。因此foo函数形参n没有必要const。当然也有时这样使用,比如int op(const int *a, const int n),a表示一个动态数组,n表示数组大小,我不希望在函数体内意外的修改了n的值,因此声明n为const形参是有用的。另外需要注意:如果是在c++中,应该尽量将不需要修改的参数定义为const引用而不应该使用传值的方法!这样能够避免复制实参,减少开销。虽然op(string s1) 和 op(const string &s1)都不会修改s1,但前者需要复制s1,而后者不需要,如果一个类型的复制代价很大时,这效率更明显!

另外需要注意的是const 指针和非const指针、const引用和非const引用是可以重载的,即int foo(const int *x) 和 int foo(int *x)可以重载,int foo(const int &x) 和 foo(int &x)可以重载,所以说重载与否只看参数类型和个数是不确切的,还需要考虑是否const指针或者引用。int foo(const int &x)可以传入右值, 而foo(int &x)不可以传入右值,因为右值是不可修改的。(注意c++11标准中右值引用 && 可以修改右值,因此int foo(int &&x)可以传入右值). 在决定调用哪个版本时,由传入的参数是否const决定!

在c++类中可以声明const成员函数,即 int foo() const {} ,这样声明说明这个函数不能修改对象成员,即this指针是const的,但注意,const成员函数仍然可以修改mutable修饰的数据成员!

总结一下:const的最主要功能是保护数据, 另外使用const引用还能提高函数运行效率,减少复制实参开销!

转载请注明:http://krystism.is-programmer.com/若有错误,请多多指正,谢谢!
  • 无匹配
  • 无匹配
John 说:
2021年11月04日 23:03

I am impressed. I don't think Ive met anyone who knows as much about this subject as you do. You are truly well informed and very intelligent. You wrote something that people could understand and made the subject intriguing for everyone. Really, great blog you have got here. fraud investigation

John 说:
2021年11月05日 13:54

I think that thanks for the valuabe information and insights you have so provided here. شراء لايكات تيك توك

John 说:
2021年11月07日 18:07

Everyone likes to have a beautiful home and garden; however, paying for all the best decorations and extras is not always easy. There are many things you can do to save money on home and garden items; you just have to know where to look and what strategies to use. Consider the following five tips when you are planning your next purchase. Better Homes and Gardens

John 说:
2021年11月07日 18:12

There are a lot of places in the world to travel, but by far the best way to get there - no matter where there is - is on a cruise. Cruises are fun, exciting, and affordable. And you get catch one just about anywhere, anytime! Travelzoo Dubai

John 说:
2021年11月07日 18:17

Brilliant idea! Take a wooden ladder and fashion it into the best Christmas tree ever! You can utilize the steps for placing gifts and ornaments... Team Trees Scam

John 说:
2021年11月08日 23:27

From the most up-to-date anime series to the hottest DC releases, your iPad will indisputably be blissful and perky with downloads that it will be extremely intricate for you to put it down. Referring to anime downloads, we have spotted and reviewed a lot of iPad comics download sites but the lucid unsurpassed winner that overthrows everyone off is Download iPad Movies on an acknowledged level. With the largest iPad downloads database ever online. download anime

John 说:
2021年11月09日 14:46

As fashion gurus, designers do perceive different fashion aspirations from people in diverse eras. To cater those changing appetites is not an easy matter. Some artists go for luxurious tastes as most modern people do show strong favor for elegance. Giant Inflatable Snow Globe

John 说:
2021年11月10日 08:40

Follow these time and money saving tips for a more trouble free experience when ordering your Custom T-shirts Printing. Learn how to be prepared for the details involved in ordering Custom Printed T-shirts. read more

John 说:
2021年11月11日 18:30

Just one short decade ago, it was virtually impossible to engage in legal sports betting if you live in the United States or in Canada. Both countries prohibit betting on almost all organized sports, in any form at all. The exceptions have always been parimutuel betting, which is only applied to two or three different sports (among them dog and horse racing). 먹튀폴리스

John 说:
2021年11月14日 15:05

Due to technological advancement and completion there are very many ways to settle your wedding party and unique wedding favors tab. Many stores prefer cash payments form it reduces the hassle of claiming the money from the payment agents as banks and credit card companies. In the latter there is a delay for the companies have to process the payments which could take days. Buy wise Verified account

John 说:
2021年11月15日 14:33

Bonus slot machines offer many ways to win and this article will show why online video slots are so attractive for players. Video slot games offer various additional bonus games, which increase your chances to win. pragmatic

John 说:
2021年11月15日 19:33

Slots can be played by pressing a spin button or by pulling the slot machine arm with the purpose of striking a winning combination of the pictures or graphics on the slot machine. Slots have become quite famous in the online casino and gambling world due to its high winning probability, variety of picture graphics, themes and effortless techniques. judi slot online

John 说:
2021年11月16日 19:14

Bounce houses are colorful, fun and the perfect entertainment for a great kid's birthday bash. Though there are hundreds of them, the best ones are those that can give your kids fun, excitement and thrills! You can have a giant inflatable in the form of a kangaroo or a tunneled castle. Whatever you choose, it is bound to give you extensive fun at an affordable price range. website

John 说:
2021年11月30日 14:25

Yes i am totally agreed with this article and i just want say that this article is very nice and very informative article.I will make sure to be reading your blog more. You made a good point but I can't help but wonder, what about the other side? !!!!!!Thanks http://69.195.78.97/login/

John 说:
2021年12月01日 18:42

There are so many benefits to quitting Weed that I don't know where to start. So I'll just dive right in and get straight to the point. buy Cali weed online

John 说:
2021年12月02日 12:59

Online sports betting on basketball games such as the NBA is rapidly growing in popularity with different people joining in for a variety of reasons. Some join for the sake of fun and to make watching the game even more thrilling whilst there are others such as the more professional gamblers who join for the sake of winning. 토토사이트

John 说:
2021年12月05日 13:26

I think I have never seen such blogs ever before that has complete things with all details which I want. So kindly update this ever for us. 707벳

John 说:
2021年12月06日 13:18

Hey, great blog, but I don’t understand how to add your site in my rss reader. Can you Help me please? 세븐 토토

John 说:
2021年12月08日 02:00

Wonderful blog post. This is absolute magic from you! I have never seen a more wonderful post than this one. You've really made my day today with this. I hope you keep this up! greatest mathematicans

John 说:
2021年12月09日 19:49

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. 모모벳

John 说:
2021年12月15日 13:14

The main goal of a Miami personal injury lawyer is to seek the right compensation and justice for the victim. Though there are lots of lawyers that are out there, it is important that you have to find the right legal representation to avoid frustrations. toxic baby formula lawyer

John 说:
2021年12月16日 13:57

The criminal validity usage is typically a very daunting thing for superstar in the crosshairs of a prosecutor, which makes it only more imperative to be embodied by a good lawyer. One way to develop your odds of receiving the best lawyer is to be arranged for your first summit. Otherwise, it can be a big excess of time for both you and the lawyer. First impressions mean a lot, and being unarranged may upshot in the lawyer not lacking to embody you. personal injury attorney nashville

John 说:
2021年12月19日 14:41

Created by LGBTQ.one, THEAPP is a cutting edge PWA (Progressive Web App) that can be used to reduce homophobic interactions with merchants by acting as an LGBTQ-friendly business directory and as a social platform. Connect with friends and find a friendly place to meet up in your city without fear of hostility. gay friendly businesses

John 说:
2021年12月31日 19:24

A lawyer is a person who is licensed by the state to provide legal services and to represent their clients in courts of law. An important task of a lawyer is to explain and interpret the law to the client. Lawyers handle a wide range of legal issues. A general lawyer is someone who handles matters of general legal relevance. Virginia lawyers are lawyers who practice law in the state of Virginia. toxicinfant formula lawsuits

John 说:
2022年1月01日 14:56

The West Palm Beach, located at the west coast of Florida, is a city full of fun. The place is widely known as the Playground for the rich. People from across the country usually come here to spend a vacation. table and chair rentals Palm Desert

John 说:
2022年1月06日 18:48

It is an inevitable truth of modern life that work and education often take us further away from home. The more miles we put between us and our family, the less we see of them. Cousins who grew up together may end up not seeing each other for years on end. Additional hints

John 说:
2022年1月06日 21:06 When one first decides to enter the world of crossbow shooting and hunting it is easy to become overwhelmed when selecting the crossbow that you want. First you will find that the prices wildly vary from as little as 50 dollars to upwards of a grand or more. Also you will find that crossbows have many different features to select from like ones that are lightweight or heavy, crossbows that come with a scope or not and so on. Thankfully with some knowledge of crossbow features and functionality you can review your different options and select the one that works best for you. crossbow arrows
John 说:
2022年1月07日 13:29

This is such a great resource that you are providing and you give it away for free. nclex test prep

John 说:
2022年2月05日 20:10

Poker is a popular card game played by anyone of any gender and any age. Players can use real or fake money, they could play in a casino or at a kitchen table. 바둑이

John 说:
2022年2月13日 12:27

I found that site very usefull and this survey is very cirious, I ' ve never seen a blog that demand a survey for this actions, very curious... aplikasi pasang togel

John 说:
2022年3月05日 18:46

I am definitely enjoying your website. You definitely have some great insight and great stories. Dragon Legend

John 说:
2022年3月19日 18:15

Do you want to know how the top internet marketers can make 1 million dollars in 24hrs? I know, it's one of those get rich quick deals huh? That's the first thing that goes through my mind when I read the question above. It's impossible as most of my friends would say. is inbox dollars legit

John 说:
2022年4月13日 14:22 We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work https://vivanet2.com/
John 说:
2022年4月18日 13:34

I need to to thank you for this very good read!! I definitely loved every little bit of it. I have you bookmarked to check out new things you post… pta approved dual sim device


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter