<分区>
我正在做一个项目,从接收到的字节构造一个对象 MyClass。字节串由一个整数(4 个字节)和一个消息(5 个字节)组成。
我创建了一个模板类以便能够轻松读取多种类型,还编写了一个模板专用函数来处理 char 数组的情况。
这是可复制粘贴到 main.cpp 文件中的代码。
#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
template <typename T>
class ByteReaderT {
public:
static const char* read(const char* source, T& dest, size_t sz)
{
std::copy(source, source + sz, &dest);
return source + sz;
}
};
template<>
inline const char* ByteReaderT<char*>::read(const char* source, char*& dest, size_t sz)
{
return std::copy(source, source + sz, dest);
}
#define DATA_SIZE 5
struct MyClass {
int num;
char* data;
MyClass(): num(0), data(new char[DATA_SIZE]) {}
void read(const char* str) {
// data is still alive and well
str = ByteReaderT<int>::read(str, num, sizeof(int));
// data is gone (data = nullptr)
// I need to reallocate memory with data = new char[DATA_SIZE];
str = ByteReaderT<char*>::read(str, data, DATA_SIZE);
}
};
int main()
{
char received_arr[] = {
'\x01', '\0', '\0', '\0', // bytes for num
'r', 'e', 'c', 'v', ' ' // bytes for data
};
MyClass c;
char* ptr = nullptr;
c.read(received_arr);
std::cout << c.num << std::endl;
std::cout << std::string(c.data) << std::endl;
return 0;
}
然而在MyClass::read
函数,我的数据指针在读取数字的前 4 个字节后重置为 nullptr。
我不知道为什么会这样。模板函数ByteReaderT<int>::read
不应触摸数据指针。
在读取 5 字节消息之前,我总是可以再次为 MyClass::read 中的数据分配内存,但这并不干净,因为我不应该这样做。
如果有人看到哪里出了问题,我们将不胜感激,因为现在我被卡住了。