c++ - 读取字节后丢失指针

标签 c++ pointers templates null byte

<分区>

我正在做一个项目,从接收到的字节构造一个对象 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 中的数据分配内存,但这并不干净,因为我不应该这样做。

如果有人看到哪里出了问题,我们将不胜感激,因为现在我被卡住了。

最佳答案

你糊涂了 std::copy std::memcpy .

std::copy是来自 <algorithm> 的算法库,它将一对迭代器作为源,一个迭代器作为输出。它将简单地遍历源范围中的每个元素,并在以 output 开头的范围内复制构造它们。 .

因为您提供了一个 int作为输出,你只能写一个元素。更进一步是未定义的行为(在您的情况下似乎正在覆盖 data 成员)。

std::copy 的示例用法:

std::vector<int> a {1, 2, 3, 4, 5};
std::array<int, 5> b;
for(int n: b)
    std::cout << n << " "; //0 0 0 0 0
std::copy(a.begin(), a.end(), b.begin());
for(int n: b)
    std::cout << n << " "; //1 2 3 4 5

std::memcpy另一方面,将简单地获取给定位置的内存内容并将其放入另一个位置,这就是您想要实现的。

示例用法:

int a = 5;
char[4] b;
std::memcpy(b, &a, 4);

关于c++ - 读取字节后丢失指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57699866/

相关文章:

c++ - 创建链表插入功能但代码没有运行

c - 在二叉树中使用指针

python - Jinja - 是否有任何内置变量来获取当前 HTML 页面名称?

map 和 multimap 之间的 C++ 模板特化

c++ - Phonon 不渲染视频

c++ - C++11 中依赖类型的模板关键字

c - 在 C 中用大括号定义一个指针?

c++ - 按值与按引用传递标准算法迭代器参数

c++ - QT 资源文件 - 图像在运行时不显示

c - 来自变量名的指针