【问题标题】:Restrict Keyword and Pointers inside structs限制结构内的关键字和指针
【发布时间】:2012-10-29 17:17:57
【问题描述】:

通过像这样使用restrict 关键字:

int f(int* restrict a, int* restrict b);

我可以指示编译器数组 a 和 b 不重叠。假设我有一个结构:

struct s{
(...)
int* ip;
};

并编写一个接受两个struct s 对象的函数:

int f2(struct s a, struct s b);

在这种情况下,我如何类似地指示编译器 a.ipb.ip 不重叠?

【问题讨论】:

    标签: c function struct restrict-qualifier


    【解决方案1】:

    您也可以在结构中使用restrict

    struct s {
        /* ... */
        int * restrict ip;
    };
    
    int f2(struct s a, struct s b)
    {
        /* ... */
    }
    

    因此编译器可以假定a.ipb.ip 用于在每次调用f2 函数期间引用不相交的对象。

    【讨论】:

      【解决方案2】:

      检查这个 pointer 示例,您可能会得到一些帮助。

      // xa and xb pointers cannot overlap ie. point to same memmpry location.
      void function (restrict int *xa, restrict int *xb)
      {
          int temp = *xa;
          *xa = *xb;
          xb = temp;
      }
      

      如果两个指针被声明为restrict,那么这两个指针不会重叠。

      已编辑

      Check this link for more examples

      【讨论】:

      • 我看不出这是如何回答问题的 - OP 清楚地知道如何使用简单的指针来解决问题,代码就在问题中。
      • 也许编写一个适用于 a.ip 和 b.ip 而不是 a 和 b 类型的函数是一个很好的解决方案。这取决于结构的性质,如果 a 和 b 是 OO 设计中使用的不完整类型,那么该方法将不起作用。
      猜你喜欢
      • 2021-06-13
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      • 2012-07-16
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      相关资源
      最近更新 更多