【问题标题】:Confusion over typedef struct in C++C++ 中 typedef 结构的混淆
【发布时间】:2011-01-23 20:58:24
【问题描述】:

我的教授编写了一个程序来模拟内存写入 L2 缓存的方式。它有几个地方我应该填写空白。我应该做的第一件事是清除每个缓存条目的有效位。他给了我们以下内容:

//number of cache entries (2^11)

#define L2_NUM_CACHE_ENTRIES (1<<11)

/***************************************************

This struct defines the structure of a single cache
entry in the L2 cache. It has the following fields:
v_d_tag: 32-bit unsigned word containing the
valid (v) bit at bit 31 (leftmost bit),
the dirty bit (d) at bit 30, and the tag
in bits 0 through 15 (the 16 rightmost bits)
cache_line: an array of 8 words, constituting a single
cache line.
****************************************************/

Typedef struct {

uint32_t v_d_tag;

uint32_t cache_line[WORDS_PER_CACHE_LINE];

} L2_CACHE_ENTRY;

//The L2 is just an array cache entries

L2_CACHE_ENTRY l2_cache[L2_NUM_CACHE_ENTRIES];

所以,据我了解,清除有效位只是意味着将其设置为零。有效位是 v_d_tag 的第 31 位,所以我应该使用位掩码 - 我想按照“v_d_tag = v_d_tag & 0x80000000;”的方式做一些事情?但我不明白的是如何为每个缓存条目完成并执行此操作。我看到了缓存条目数组(l2_cache),但我看不到 v_d_tag 与它的关系。

谁能给我解释一下?

【问题讨论】:

  • 你的问题和你的标题有什么关系?
  • 好吧,我很确定我对代码的不理解与 typedef 设置有关,我不知道如何简洁地表达我的问题的细节以获得标题,所以我就去了。抱歉,如果我违反了礼仪,那不是我的本意——我只是不知道我在说什么。 ^^;

标签: c++ arrays bitmask


【解决方案1】:

typedef struct 在 C++ 中是多余的,就像我看到的 #define 一样,它们可能是 static const int。

为了清除它们,你会想要这样做

for(int i = 0; i < L2_NUM_CACHE_ENTRIES; i++)
    l2_cache[i].v_d_tag &= 0x80000000;

【讨论】:

    【解决方案2】:

    结构以 C 的方式定义,因为在 C 中,typedef 声明一个结构是一种常见的习惯用法,这样它就可以用作一个类型,而不必在每个引用上写 struct L2_CACHE_ENTRY。在 C++ 中不再需要这个习惯用法,因为 struct 标记将作为单独的类型工作。

    简而言之,在 C++ 中你可以对待

    typedef struct {
    
    uint32_t v_d_tag;
    
    uint32_t cache_line[WORDS_PER_CACHE_LINE];
    
    } L2_CACHE_ENTRY;
    

    完全一样

    struct L2_CACHE_ENTRY{
    
    uint32_t v_d_tag;
    
    uint32_t cache_line[WORDS_PER_CACHE_LINE];
    
    };
    

    【讨论】:

    • 正确,但根本没有回答问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    相关资源
    最近更新 更多