【发布时间】:2015-04-06 04:41:02
【问题描述】:
我有一个函数接受对 void** 的引用。
bool boExecute(void**& vOutParameter);
我尝试在vOutParameter中写入一些值,但是当我在main()中检查时,该值没有写入。
在这种情况下,& 指的是什么?是对指针的引用还是对指针的引用?
在boExecute里面,我是这样添加的:
bool boExecute(void**& vOutParameter)
{
Struct_Type* Out = new Struct_Type[4];
for (int i=0; i<4; ++i)
{
memcpy(&(Out[i]), Referenced_Struct[i], sizeof(Struct_Type));
}
*vOutParameter = reinterpret_cast<void*>Out;
Out = null;
return true;
}
Referenced_Struct 是 Struct_Type** 类型,它有两个成员,int32_val 和 int64_val。
主要内容:
void main(void)
{
void **test;
boExecute(test);
Struct_Type** temp = reinterpret_cast<Struct_Type**>(test);
Struct_Type* temp1 = *temp;
for (int i=0; i<4; ++i)
{
printf("%d, %d", temp1[i].int32_val, temp1[i].int64_val);
}
}
我在做什么有问题吗? 当我更改*vOutParameter 时,*vOutParameter 的内容应该在它退出函数时更新,对吧?
【问题讨论】:
-
vOutParameter = ...将修改您从main()传递的指针(并出于任何原因选择不包含在您的问题中)。您说,“我有一个接受void*的函数” - 不,该函数接受对void**的引用。它们昼夜不同。 -
但我没有更改 vOutParameter。我只更改 *vOutParameter 的引用。这是否意味着 *vOutParameter 包含的任何内容在函数调用后都会丢失?
-
“我没有更改
vOutParameter...” - 完全正确。这就是为什么我们在来自main()的调用中仍然 看不到的指针没有改变。你为什么认为你需要一个void**&?我认为您可以简单地使用void**或void*&,但如果不知道来自main()的电话的期望,就不可能说出来。已发布问题的答案是什么&引用,它是对指针到指针到void的引用。 -
问题可能出在对
memcpy的调用中,请尝试将sizeof(Struct_Type*)更改为sizeof(Struct_Type)。 -
使用结构赋值而不是
memcpy,如果类型不是可简单复制的,那么 memcpy 会导致未定义的行为。
标签: c++ pointers pass-by-reference