C++ 我应该如何返回我的字节数组?

Yae*_*ger 0 c++ memory arrays heap-memory

我有一个名为 X(例如)的类和一个公共函数 toBytes(),它返回对象的一些自定义二进制表示。

我的问题是:我应该如何返回这个字节数组?

目前,我有这个:

uint8_t* X::toBytes()
{
    uint8_t* binData = new uint8_t[...];

    // initialize the byte array

    return binData;
}
Run Code Online (Sandbox Code Playgroud)

The problem (or as problem considered by me as an inexperienced c++ programmer) here is that it's allocating the memory on the heap and should be freed at some point which I don't think is practical. Either the class X should free this memory in its destructor in some cumbersome way or the caller should free it. How is the caller supposed to know it is responsible for freeing the memory? It doesn't even know if it's heap memory, right?

Kinda stuck here :/

EDIT:

I just thought of a possible solution: let the caller supply the memory as in a pointer to a byte array and initialize that array. This would solve the problem, right?

Ker*_* SB 5

I'd provide one generic solution and one convenience wrapper:

#include <iterator>
#include <vector>

template <typename OutIter>
void writeBytes(OutIter iter)
{
    for (...) { *iter = data(); ++iter; }
}

std::vector<uint8_t> toBytes()
{
    std::vector<uint8_t> result;
    writeBytes(std::back_inserter(result));
    return result;
}
Run Code Online (Sandbox Code Playgroud)

The generic version allows the user to interface with any kind of container they choose, and the convenience "vector" version allows the user to write something like for (auto b : toBytes()).