mardi 3 octobre 2017

Handling data on wire using unique_ptr

When receiving data on wire and sending it to upper applications, normally, in C style, we have a struct for example with a void*:

struct SData{
//... len, size, version, msg type, ...
void* payload;
}

Later in the code, after error checking and mallocating, ..., we can do something as:

if(msgType == type1){
    struct SType1* ptr = (struct SType1*) SData->payload;
}

In C++, an attempt to use unique_ptr fails in the following snippet:

struct SData{
// .. len, size, version, msg type, ...
std::unique_ptr<void> payload;
}

But as you know, this will cause:

error: static assertion failed: can't delete pointer to incomplete type

Is there a way to use smart pointers to handle this?

One solution I found is here: Should std::unique_ptr<void> be permitted

Which requires creating a custom deleter:

void HandleDeleter(HANDLE h)
{
    if (h) CloseHandle(h);
}

using

UniHandle = unique_ptr<void, function<void(HANDLE)>>; 

This will require significantly more additional code (compared to the simple unsafe C Style), since for each type of payload there has to be some logic added.

Aucun commentaire:

Enregistrer un commentaire