将引用传递给指向void类型的指针

时间:2015-04-06 04:41:03

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

我有一个函数接受对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的内容应该在它退出函数时更新,对吗?

1 个答案:

答案 0 :(得分:5)

  

我做的事情有什么问题吗?

你应该使用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(返回值优化),返回整个向量时没有性能问题。所以你可以知道你的记忆是安全的。


  

在这种情况下,&amp;参考?它是对指针的引用还是对指针指针的引用?

一般来说,T&是对T的引用。这意味着void**&是对void**的引用,void是指向{{1}}的指针。

相关问题