传递对指向 void 类型的指针的指针的引用

Passing a reference to a pointer to pointer of type void

本文关键字:指针 类型 引用 void      更新时间:2023-10-16

我有一个接受对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 的内容应该在函数外更新,对吧?

我正在做的事情有问题吗?

您应该实际使用 C++ 重写函数,而不是使用奇怪的 C 语义,为错误和 out 参数提供不必要的布尔返回值:

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;
}

现场演示

请注意,由于 RVO(返回值优化(,返回整个向量时没有性能问题。所以你可以睡觉,知道你的记忆是安全的。


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

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

相关文章: