c++ - 在 vector 中存储二进制数据

标签 c++

我有给定的类:

class Buffer
{
public:
    Buffer(int capacity);
    ~Buffer();

    int size, capacity, client;
    int write(const char *data, int bytes);
    int read(char *data, int bytes);
    char *data_;
private:
    int beg_index_, end_index_, size_, capacity_;

};

Buffer::Buffer(int capacity) {
    beg_index_ = 0; 
    end_index_ = 0; 
    size_ = 0;      
    capacity_ = capacity;
    data_ = new char[capacity];
}

Buffer::~Buffer()
{
    delete[] data_;
}

int Buffer::write(const char *data, int bytes)
{
    if (bytes == 0) return 0;

    int capacity = capacity_;
    int bytes_to_write = std::min(bytes, capacity - size_);
    if (bytes_to_write <= capacity - end_index_)
    {

        memcpy(data_ + end_index_, data, bytes_to_write); //**ERROR
        end_index_ += bytes_to_write;
        if (end_index_ == capacity) end_index_ = 0;
    }
//(...)

我想将二进制数据存储在一个 vector 中,如下所示:

std::vector<Buffer> buffers_audio(2,Buffer(1000000));

void buffering_mem(char* chunk,int size_chunk, int close_file, int client, int total_size){
buffers_audio[client].write(chunk, size_chunk);
}

buffering_mem 是一个从 NodeJS 调用的函数,应该单独存储来自几个客户端的信息(有时,该函数从客户端 1 调用,有时从客户端 20 调用)。 但我在 memcpy 中收到错误“未处理的异常...访问冲突写入位置”。而且我不愿意复制二进制数据。任何人都可以解释为什么我会收到此错误?

最佳答案

当这段代码被执行时:

 std::vector<Buffer> buffers_audio(2,Buffer(1000000));

发生以下情况:

Buffer.ctor(int); //creates a default value on stack   
Buffer.ctor(const &Buffer) // initialize element #1    
Buffer.ctor(const &Buffer) // initialize element #2
Buffer.dtor(); // Destroy the temp instance.

默认复制构造函数复制所有缓冲区的字段包括 data_ 指针值。但是,它不会克隆引用的数据。结果是 3 个对象实例指向同一内存,这很可能不是预期的。

要修复它,可以编写一个适当的复制构造函数。一个更简单的解决方案是使用 vector 来管理数据。此外,为了减少对象实例化的数量,请使用 emplace_back()

class Buffer
{
 public:
    explicit Buffer(int capacity): data(capacity){ };
    char* data() {return data_.data();}
 private:
    std::vector<char> data_;
    ...
 };


std::vector<Buffer> buffers_audio();

buffers.emplace_back(100000); // call Buffer(int) in-place
buffers.emplace_back(100000);

关于c++ - 在 vector 中存储二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32569024/

相关文章:

C++(和 openCV): Accumulating a number of Mat in vector<Mat>

c++ - 适用于 Vista/Windows 7 的凭证管理器

c++ - 获取STL vector C++的地址

c++ - 这是重载提供与非静态成员函数相同接口(interface)的静态成员函数的优雅方法吗?

c++ windows通过USB串行获取USB端口和集线器

c++ - CMake 无法确定目标 : fileloader 的链接器语言

Java C++代码转换

c++ - 如何用字符串中的数据替换访问说明符?

c++ - Thrust中是否有 boost 计算功能的类比?

c++ - 无法将某些函数从一个文件移动到另一个 C++