Chinaunix首页 | 论坛 | 博客
  • 博客访问: 850949
  • 博文数量: 213
  • 博客积分: 5048
  • 博客等级: 大校
  • 技术积分: 1883
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-14 10:14
文章分类

全部博文(213)

文章存档

2011年(4)

2010年(55)

2009年(47)

2008年(107)

我的朋友

分类: C/C++

2008-10-24 20:38:53

想了解的可以先看下面一片文章,英文的,但是讲的不错
'Restrict' Pointers
One of the new features in the recently approved C standard C99, is the restrict pointer qualifier. This qualifier can be applied to a data pointer to indicate that, during the scope of that pointer declaration, all data accessed through it will be accessed only through that pointer but not through any other pointer. The 'restrict' keyword thus enables the compiler to perform certain optimizations based on the premise that a given object cannot be changed through another pointer. Now you're probably asking yourself, "doesn't const already guarantee that?" No, it doesn't. The qualifier const ensures that a variable cannot be changed through a particular pointer. However, it's still possible to change the variable through a different pointer. For example:

 

  void f (const int* pci, int *pi;); // is *pci immutable?
  {
    (*pi)+=1; // not necessarily: n is incremented by 1
     *pi = (*pci) + 2; // n is incremented by 2
  }
  int n;
  f( &n, &n);
 

In this example, both pci and pi point to the same variable, n. You can't change n's value through pci but you can change it using pi. Therefore, the compiler isn't allowed to optimize memory access for *pci by preloading n's value. In this example, the compiler indeed shouldn't preload n because its value changes three times during the execution of f(). However, there are situations in which a variable is accessed only through a single pointer. For example:

 

  FILE *fopen(const char * filename, const char * mode);

The name of the file and its open mode are accessed through unique pointers in fopen(). Therefore, it's possible to preload the values to which the pointers are bound. Indeed, the C99 standard revised the prototype of the function fopen() to the following:

 
  /* new declaration of fopen() in  */
  FILE *fopen(const char * restrict filename, 
                        const char * restrict mode);

Similar changes were applied to the entire standard C library: printf(), strcpy() and many other functions now take restrict pointers:

 
  int printf(const char * restrict format, ...);
  char *strcpy(char * restrict s1, const char * restrict s2);

C++ doesn't support restrict yet. However, since many C++ compilers are also C compilers, it's likely that this feature will be added to most C++ compilers too.

www.devx.com/tips/Tip/13825
说点我的理解吧,一个指针就算他被设置成const,可是还是可能通过其他相同指向的指针改变这个指向里面的值,就像文中说的pci虽然是const,但是可以通过pi改变其中的值,如果一个内存就只能被一个指针指向的时候,我们就可以在前面加restrict,这样编译器就可以做一定的优化。查相关资料时还看见有人把restrict和volatile看做相反的两个前缀,我觉得有些道理,volatile修饰的变量就是因为易变显示要求编译器不要优化,感觉是不是没有用volatile修饰的是不是默认是restrict呢?我现在也没清楚。感觉是。呵呵菜鸟的感觉
阅读(2703) | 评论(0) | 转发(0) |
0

上一篇:Linux解释器原理

下一篇:getchar的返回值

给主人留下些什么吧!~~