【问题标题】:What's the grammar meaning of '&buf_pool->watch[0]'?'&buf_pool->watch[0]' 的语法含义是什么?
【发布时间】:2015-10-26 10:11:01
【问题描述】:

我在这里阅读了mysql的innodb缓冲区源代码buf0buf.cc中的代码:

link from git hub

我得到了这个:

&buf_pool->watch[0]

声明的价值是什么?地址?还是其他值?

代码是什么意思?(语法含义)

【问题讨论】:

  • 认为这个表达式有什么作用?你为什么这么认为?
  • @JoachimPileborg,语法层面的代码含义对我来说已经足够了。

标签: c++ pointers memory-address


【解决方案1】:

由于operator precedence,这个表达式被解析为:

&( (buf_pool->watch)[0] )

英文中,该值为watch成员容器在buf_pool中的第一个元素的地址。

【讨论】:

  • 不应该是&( buf_pool->watch[0] )吗?解析(buf_pool->watch)[0] 将具有作用于struct buf_pool_t* 类型的下标,而在buf_pool->watch[0] 中它应该对watch 的类型产生影响。
  • buf_pool->watch 将返回一个缓冲区。因此,可以在返回后对其进行索引。这个“翻译”是有效的。
【解决方案2】:

你可以找出来。

首先,让我们获取buf_bool 变量并查找它的声明。上面几行可以看到,它是一个函数参数:

const buf_pool_t* buf_pool

这意味着我们必须找到buf_pool_t 类型的定义。仅通过全文搜索,不会显示类型定义。然而,谷歌搜索“mysql buf_pool_t”让我们找到http://www.iskm.org/mysql56/structbuf__pool__t.html,这反过来告诉我们该类型是在一个名为buf0buf.h的文件中定义的。该文件也包含在您链接到的源文件中:

#include "buf0buf.h"

它确实包含我们正在寻找的定义,并且该定义包括一个名为 watch 的成员:

struct buf_pool_t{

(...)

         buf_page_t*                     watch;

(...)

};

watch 是指向buf_page_t 的指针。

所以如果我们回到你问题中的陈述:

&buf_pool->watch[0]

watch 被解释为指向buf_page_t 数组的第一个元素的指针,watch[0] 是第一个元素本身,并且 address-of 运算符产生一个指向该第一个元素的指针。

所以整个语句读作:

指向buf_page_t 数组的第一个元素的指针。

奇怪的是,&buf_pool->watch[0] 等于 buf_pool->watch。这是一个简单的 (C++11) 玩具程序来验证所有这些:

#include <iostream>
#include <typeinfo>

using buf_page_t = int;

struct buf_pool_t {
    buf_page_t* watch;
};

int main()
{
    const buf_pool_t example = { new buf_page_t[1] };
    const buf_pool_t* buf_pool = &example; 

    std::cout << typeid(&buf_pool->watch[0]).name() << "\n";
    std::cout << typeid(buf_pool->watch).name() << "\n";
    std::cout << (&buf_pool->watch[0] == buf_pool->watch) << "\n"; // prints 1
}

【讨论】:

    【解决方案3】:

    &amp;buf_pool-&gt;watch[0]是结构体buf_bool中包含的watch的成员0的地址。这是watch 本身。 之所以这样解析,是因为整个 buf_pool-&gt;watch[0] 都在 &(地址)符号下。

    你可以用这个sn-p检查:

    #include <iostream>
    #include <stdio.h>
    using namespace std;
    
    struct hello_t
    {
        int before;
        int array[5];
    };
    
    int main() {
        // your code goes here
        struct hello_t hello;
        hello.array[0] = 100;
        struct hello_t* ptr_hello;
        ptr_hello = &hello;
        printf("ptr_hello = %X\n", ptr_hello);
        printf("&ptr_hello = %X\n", &ptr_hello);
        printf("&ptr_hello->before = %X\n", &ptr_hello->before);
        printf("&ptr_hello->array[0] = %X\n", &ptr_hello->array[0]);
    
        printf("");
    
        return 0;
    }
    

    https://ideone.com/fwDnoz

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 2018-12-11
      • 2022-07-07
      • 2021-07-19
      • 2011-09-17
      相关资源
      最近更新 更多