本人非计算机专业的工科学生,今天读一个开源软件的源代码,遇到了一个奇怪的强制类型转换,代码如下:
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,我想问的问题是:
这个类型转换是把二维指针变量转换成了一维指针变量?
getData函数在程序中的作用是为了给导入field指向的内存赋值,比如我在getData函数外定义了double* U,然后用getData(name, type, U, step)是为了给U指向的内存赋值;那么我想问的是经过(void&)U转换会对U产生什么影响?
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 discardedconst
.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 ofgetData
,&U
can be compiled, but not.If it is called correctly, and
getData
and related functions are implemented correctly (the object referenced byfield
is not modified), then there will be no impact onU
.What is unreasonable here is that the type conversion at
(void *&)
discardsconst
, semantically making the object referenced byfield
become changeable (possibly modifying the value of U or modifying an immutable object, resulting in Undefined behavior), but the expression ofgetData
declaration is "field
cannot be changed". According togetData
's description, there is actually no need to discard thisconst
.