"&buf_pool->watch[0]"的语法含义是什么?

What's the grammar meaning of '&buf_pool->watch[0]'?

本文关键字:语法 是什么 buf pool- gt watch      更新时间:2023-10-16

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

链接到git hub

我得到了这个:

&buf_pool->watch[0]

语句的值是多少?地址吗?或者另一个值?

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

由于运算符优先,该表达式解析为:

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

buf_poolwatch成员容器的第一个元素的地址。

你可以找到。

首先,让我们以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]是第一个元素本身,寻址操作符返回指向第一个元素的指针。

所以整个语句读作:

指向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
}

&buf_pool->watch[0]buf_bool结构体中watch的成员0的地址。也就是watch本身。这样解析是因为整个buf_pool->watch[0]都在&(地址)符号

你可以用下面的代码片段检查:

#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 = %Xn", ptr_hello);
    printf("&ptr_hello = %Xn", &ptr_hello);
    printf("&ptr_hello->before = %Xn", &ptr_hello->before);
    printf("&ptr_hello->array[0] = %Xn", &ptr_hello->array[0]);
    printf("");
    return 0;
}
https://ideone.com/fwDnoz