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

chr*_* yo 3 c++ pointers pass-by-reference

我有一个函数接受void**的引用.

bool boExecute(void**& vOutParameter);
Run Code Online (Sandbox Code Playgroud)

我试图在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;
}
Run Code Online (Sandbox Code Playgroud)

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);
   }
}
Run Code Online (Sandbox Code Playgroud)

我正在做的事情有什么不对吗?当我更改*vOutParameter时,*vOutParameter的内容应该在它退出函数时更新,对吧?

Sho*_*hoe 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;
}
Run Code Online (Sandbox Code Playgroud)

Live demo

请注意,由于RVO(返回值优化),返回整个向量没有性能问题.因此,您可以知道您的记忆是安全的.


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

一般来说T&是参考T.这意味着void**&是所涉及的参考void**这是指针的指针void.