c++ - 指针容器的指针别名

标签 c++ pointers stl containers alias

我了解到指针别名可能会损害性能,并且 __restrict__ 属性(在 GCC 中,或其他实现中的等效属性)可能有助于跟踪哪些指针应该或不应该别名。同时,我还了解到 GCC 的 valarray 实现存储了一个 __restrict__ 指针(https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.1/valarray-source.html 中的第 517 行),我认为这暗示了编译器(和负责任的用户)可以假设私有(private)指针在 valarray 方法中的任何地方都没有别名。

但是如果我们给一个指向 valarray 对象的指针起别名,例如:

#include <valarray>

int main() {
    std::valarray<double> *a = new std::valarray<double>(10);
    std::valarray<double> *b = a;
    return 0;
}

a 的成员指针也是别名的说法有效吗? b 的存在是否会损害 valarray 方法本来可以受益的任何优化? (指向优化的指针容器是不好的做法吗?)

最佳答案

让我们首先了解别名如何影响优化。

考虑这段代码,

void
process_data(float *in, float *out, float gain, int nsamps)
{
    int i;
    for (i = 0; i < nsamps; i++) {
        out[i] = in[i] * gain;
    }
}

In C or C++, it is legal for the parameters in and out to point to overlapping regions in memory.... When the compiler optimizes the function, it does not in general know whether in and out are aliases. It must therefore assume that any store through out can affect the memory pointed to by in, which severely limits its ability to reorder or parallelize the code (For some simple cases, the compiler could analyze the entire program to determine that two pointers cannot be aliases. But in general, it is impossible for the compiler to determine whether or not two pointers are aliases, so to be safe, it must assume that they are).


来到你的代码,

#include <valarray>

int main() {
    std::valarray<double> *a = new std::valarray<double>(10);
    std::valarray<double> *b = a;
    return 0;
}

因为 ab 是别名。 valarray 使用的底层存储结构也会被别名化(我认为它使用的是数组。对此不太确定)。因此,以类似于上面显示的方式使用 ab 的代码的任何部分都不会受益于并行化和重新排序等编译器优化。请注意,b 的存在不会影响优化,但会影响您的使用方式。

学分: 引用部分和代码取自 here .这也应该作为有关该主题的更多信息的良好来源。

关于c++ - 指针容器的指针别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30288985/

相关文章:

c++ - 用于整数下限和上限查询的快速数据结构?

C++语言符号分隔符

c - WIN32和其他c字符串的区别

c - 多函数调用期间指向当前节点的节点指针

c - 提升指向未定义位置的指针是否合法?

c++ - 循环 vector vector 并附加到新 vector

c++ - 函数返回值错误

c++ - 是否存在使用 catch all 子句 : catch (. ..) 的情况?

c++ - Lua:多次调用返回字符串的 Lua 函数。如何做到这一点,以便有交叉到下一个实例的字段

c++ - 从 Google 模拟中的模拟对象返回模拟对象