码迷,mamicode.com
首页 > 其他好文 > 详细

区分const指针

时间:2015-07-05 23:55:13      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

 

Read it backwards...

  • int* - pointer to int
  • int const * - pointer to const int
  • int * const - const pointer to int
  • int const * const - const pointer to const int

Now the first const can be on either side of the type so:

  • const int * == int const *
  • const int * const == int const * const

If you want to go really crazy you can do things like this:

  • int ** - pointer to pointer to int
  • int ** const - a const pointer to a pointer to an int
  • int * const * - a pointer to a const pointer to an int
  • int const ** - a pointer to a pointer to a const int
  • int * const * const - a const pointer to a const pointer to an int
  • ...

And to make sure we are clear on the meaning of const

const int* foo;
int *const bar; //note, you actually need to set the pointer 
                //here because you can‘t change it later ;)

foo is a variable pointer to a constant int. This lets you change what you point to but not the value that you point to. Most often this is seen with cstrings where you have a pointer to a const char. You may change which string you point to but you can‘t change the content of these strings. This is important when the string itself is in the data segment of a program and shouldn‘t be changed.

bar is a const or fixed pointer to a value that can be changed. This is like a reference without the extra syntactic sugar. Because of this fact, usually you would use a reference where you would use a T* const pointer unless you need to allow null pointers.

区分const指针

标签:

原文地址:http://www.cnblogs.com/plummithly/p/4623277.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!