【问题标题】:Passing a reference to a pointer to pointer of type void传递对指向 void 类型指针的指针的引用
【发布时间】: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**&amp;?我认为您可以简单地使用void**void*&amp;,但如果不知道来自main() 的电话的期望,就不可能说出来。已发布问题的答案是什么&引用,它是对指针到指针到void的引用。
  • 问题可能出在对memcpy的调用中,请尝试将sizeof(Struct_Type*)更改为sizeof(Struct_Type)
  • 使用结构赋值而不是memcpy,如果类型不是可简单复制的,那么 memcpy 会导致未定义的行为。

标签: c++ pointers pass-by-reference


【解决方案1】:

我的操作有问题吗?

你应该用 C++ 重写函数,而不是奇怪的 C 语义,为错误和输出参数使用不必要的布尔返回值:

template<typename It>
std::vector<Struct_type> boExecute(It Reference_begin, It Reference_end)
{
    std::vector<Struct_type> Out;
    std::copy(Reference_begin, Reference_end, std::back_inserter(Out));
    return Out;
}

Live demo

请注意,由于 RVO(返回值优化),返回 整个 向量没有性能问题。这样你就可以在知道你的记忆是安全的情况下睡觉了。


在这种情况下,& 指的是什么?是对指针的引用还是对指针的引用?

一般T&amp; 是对T 的引用。这意味着void**&amp; 是对void** 的引用,void** 是指向void 的指针。

【讨论】:

  • 请注意,这最终可以简化为return std::vector&lt;Struct_type&gt;(begin,end);,因此首先会质疑该功能的必要性。
猜你喜欢
  • 1970-01-01
  • 2013-10-24
  • 2021-07-22
  • 1970-01-01
  • 2012-03-25
  • 2021-07-19
  • 2016-03-21
  • 2023-02-09
  • 1970-01-01
相关资源
最近更新 更多