gpt4 book ai didi

c++ - 这里访问了多少个不同的指针/间接级别?

转载 作者:太空宇宙 更新时间:2023-11-04 11:33:23 24 4
gpt4 key购买 nike

我有四个类代表继承和组合层次结构:

class A{
//Structure here not important
}

class B : public A{
int a;
shared_ptr<C> c;
}

class C{
shared_ptr<D> d;
}

class D{
std::list<int> e;
}

然后我有一个 vector<shared_ptr<A>> ,我迭代并总结了 *begin()来自两个 D std::list<int> 的值对象:

for(int i = 0; i< vec.size(); i++){
shared_ptr<B> b = vec[i];
shared_ptr<C> c = b->c;
sum += *(c->d->e.begin());
}

我正在尝试计算每个循环迭代可以进行多少次单独的缓存行访问(如果我们假设最坏的情况是每个间接级别/指针存储在不同的缓存行中)。

到目前为止,我已经计算出每次迭代有 7.25 个不同的缓存行:

  1. 访问 shared_ptr<A>vec[i] (这是 0.25 因为 sizeof(shared_ptr<A>)/64 )
  2. 访问 A对象 vec[i]指向
  3. 访问 shared_ptr<C> c指向
  4. 访问 C对象 c指向
  5. 访问 shared_ptr<D> d的对象
  6. 访问对象 D d
  7. 正在访问 dstd::list<int> e指针
  8. 正在访问 d*begin()数据

有什么我遗漏的吗?我不确定在循环内的堆栈上创建的对象(bc)是否可以存储在指向它们正在访问的指针(vec[i]b->c)的不同缓存行中。

最佳答案

已添加答案以补充评论中的对话

这是带有一些注释的循环:

for(int i = 0; i< vec.size(); i++){
shared_ptr<B> b = vec[i]; // create 1 copy of vec[i] - increments share cout
shared_ptr<C> c = b->c; // create 1 copy of b->c - increments share cout
sum1 += *(c->d1->e.begin()); // merely dereference pointer
sum2 += *(c->d2->e.begin()); // merely dereference pointer
}

你可以保存一些拷贝,因此如果你这样写,一些缓存行会丢失:

for(int i = 0; i< vec.size(); i++){
// take reference only - no copy.
//const means I promise not to modify the pointer object.
const shared_ptr<B>& b = vec[i];

// take reference only - no copy.
//const means I promise not to modify the pointer object.
const shared_ptr<C>& c = b->c; // dereference b (which is really vec[i])

sum1 += *(c->d1->e.begin()); // merely dereference pointer
sum2 += *(c->d2->e.begin()); // merely dereference pointer
}

关于c++ - 这里访问了多少个不同的指针/间接级别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23748925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com