并帮助限制使用C,如果指针已标记const的? [英] Does restrict help in C if a pointer is already marked const?

查看:93
本文介绍了并帮助限制使用C,如果指针已标记const的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道:当我添加限制的指针,我告诉编译器指针不是另一个指针的别名。假设我有这样一个功能:

Just wondering: When I add restrict to a pointer, I tell the compiler that the pointer is not an alias for another pointer. Let's assume I have a function like:

// Constructed example
void foo (float* result, const float* a, const float* b, const size_t size)
{
     for (size_t i = 0; i < size; ++i)
     {
         result [i] = a [0] * b [i];
     }
}

如果编译器必须假定结果可能与重叠,它有一个每次都重新获取。但是,正如 A 标记常量,编译器也可以假定是固定的,所以取它曾经是ok了。

If the compiler has to assume that result might overlap with a, it has to refetch a each time. But, as a is marked const, the compiler could also assume that a is fixed, and hence fetching it once is ok.

问题是,在这样的情况下,什么是推荐的方式工作,并限制?我当然不希望编译器 A 每次重新获取,但我无法找到有关如何限制应该在这里工作。

Question is, in a situation like this, what is the recommend way to work with restrict? I surely don't want the compiler to refetch a each time, but I couldn't find good information about how restrict is supposed to work here.

推荐答案

您指针为常量,见人就调用你的函数,你不会碰这对准通过该变量的数据。不幸的是,编译器仍然不会知道结果是常量指针的别名。您可以随时使用非const指针作为一个const指针。例如,很多功能需要一个const char(即字符串)的指针作为参数,但你可以,如果你愿意,它传递一个非const指针,功能仅仅是让你它不会使用特定的一个承诺指针改变任何东西。

Your pointer is const, telling anyone calling your function that you won't touch the data which is pointed at through that variable. Unfortunately, the compiler still won't know if result is an alias of the const pointers. You can always use a non-const pointer as a const-pointer. For example, a lot of functions take a const char (i.e. string) pointer as a parameter, but you can, if you wish, pass it a non-const pointer, the function is merely making you a promise that it wont use that particular pointer to change anything.

基本上,更贴近你的问题,你需要为了限制添加到A和B承诺,凡使用该功能不会在结果传递作为别名为A或B的编译器。假设,当然,你可以做这样的承诺。

Basically, to get closer to your question, you'd need to add restrict to a and b in order to 'promise' the compiler that whoever uses this function won't pass in result as an alias to a or b. Assuming, of course, you're able to make such a promise.

这篇关于并帮助限制使用C,如果指针已标记const的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆