c++ - 二维数组指针double **&field经过这个转换 (void*&) field 是什么意思?
巴扎黑
巴扎黑 2017-04-17 15:33:12
0
1
1074

本人非计算机专业的工科学生,今天读一个开源软件的源代码,遇到了一个奇怪的强制类型转换,代码如下:

void twoWayMPI::getData
(
    word name,
    word type,
    double ** const& field,
    label step
) const
{
    char* charName = wordToChar(name);
    char* charType = wordToChar(type);
    data_liggghts_to_of(charName,charType, lmp, (void*&) field, (char *)"double");
}

data_liggghts_to_of函数代码如下:

void data_liggghts_to_of(char *name,char *type,void *ptr,void *&data,char* datatype)
{
    //LAMMPS *lmp = (LAMMPS *) ptr;
    FixCfdCoupling* fcfd = (FixCfdCoupling*)locate_coupling_fix(ptr);
    fcfd->get_dc()->push(name,type,data,datatype);
}

getData函数调用data_liggghts_to_of函数时用了个奇怪的强制类型转换(void*&) field,我想问的问题是:

  1. 这个类型转换是把二维指针变量转换成了一维指针变量?

  2. getData函数在程序中的作用是为了给导入field指向的内存赋值,比如我在getData函数外定义了double* U,然后用getData(name, type, U, step)是为了给U指向的内存赋值;那么我想问的是经过(void&)U转换会对U产生什么影响?

巴扎黑
巴扎黑

reply all(1)
刘奇

Is this type conversion converting a two-dimensional pointer variable into a one-dimensional pointer variable?

Yes, this type conversion converts the type of expression field from a second-level pointer to a first-level pointer, and the value category is an lvalue (if no & is added, it is an rvalue). Also discarded const.

The role of the getData function in the program is to assign a value to the memory pointed to by the imported field. For example, I defined double* U outside the getData function, and then used getData(name, type, U, step) to assign The memory assignment pointed to by U; then what I want to ask is what impact will the (void&)U conversion have on U?

cannot be called like this because the type of the actual parameter (double *) and the type of the formal parameter (double ** const) do not match. You can consider calling it through (double ** &)U or (double **)U. According to the description of getData, &U can be compiled, but not.

If it is called correctly, and getData and related functions are implemented correctly (the object referenced by field is not modified), then there will be no impact on U.

What is unreasonable here is that the type conversion at (void *&) discards const, semantically making the object referenced by field become changeable (possibly modifying the value of U or modifying an immutable object, resulting in Undefined behavior), but the expression of getData declaration is "field cannot be changed". According to getData's description, there is actually no need to discard this const.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template