简体   繁体   中英

Passing a reference to a pointer to pointer of type void

I have a function that accepts a reference to void**.

bool boExecute(void**& vOutParameter);

I tried to write some value in vOutParameter, but when I checked it in the main(), the value was not written.

In this case, what does & referencing to? Is it a reference to a pointer or a reference to a pointer to pointer?

Inside boExecute, I add it like this:

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 is of type Struct_Type**, which had two members, int32_val and int64_val.

Contents of main:

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

Is there something wrong in what I'm doing? When I changed *vOutParameter, the contents of *vOutParameter should be updated when it goes out of the function, right?

Is there something wrong in what I'm doing?

You should rewrite the function actually using C++, instead of weird C semantic with unnecessary boolean return values for errors and out parameters:

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

Notice that there's no performance issue in returning the whole vector because of RVO (Return Value Optimization). So you can sleep knowing that your memory is safe.


In this case, what does & referencing to? Is it a reference to a pointer or a reference to a pointer to pointer?

In general T& is a reference to T . Which means that void**& is a reference to a void** which is a pointer to pointer to void .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM