简体   繁体   English

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

[英]C++ How should I return my byte array?

I've got a class named X (eg) and a public function toBytes() which returns some custom binary representation of the object.我有一个名为 X(例如)的类和一个公共函数 toBytes(),它返回对象的一些自定义二进制表示。

My problem is: how should I return this byte array?我的问题是:我应该如何返回这个字节数组?

Currently, I have this:目前,我有这个:

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

    // initialize the byte array

    return binData;
}

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.这里的问题(或者我作为一个没有经验的 c++ 程序员认为的问题)是它在堆上分配内存,应该在我认为不切实际的某个时候释放。 Either the class X should free this memory in its destructor in some cumbersome way or the caller should free it.要么类 X 应以某种麻烦的方式在其析构函数中释放此内存,要么调用者应释放它。 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?这样就能解决问题了吧?

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

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()) .通用版本允许用户与他们选择的任何类型的容器交互,而方便的“向量”版本允许用户编写类似for (auto b : toBytes())

Assuming the size of the array is not known at compile time, use an std::vector and return it:假设在编译时不知道数组的大小,使用std::vector并返回它:

std::vector<uint8_t> toBytes()
{
  std::vector<uint8_t> binData = ....;
  return binData;
}

If the size is known at compile time, then you may prefer to use an std::array :如果在编译时已知大小,那么您可能更喜欢使用std::array

std::array<uint8_t, 42> toBytes()
{
  std::array<uint8_t, 42> binData = ....;
  return binData;
}

The std::vector method would most likely be the preferred choice. std::vector方法很可能是首选。 An alternative would be to return a std::unique_ptr :另一种方法是返回std::unique_ptr

std::unique_ptr<uint8_t[]> toBytes()
{
    std::unique_ptr<uint8_t[]> result(new uint8_t[size]);
    // ...
    return result;
}

This would only be useful if there was some limitation that prevented you from being able to utilize std::vector .这仅在存在某些限制使您无法使用std::vector时才有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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