Store Binary Data in Vector

时间:2015-09-14 15:58:11

标签: c++

I have the given class:

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;
    }
//(...)

I want to store the binary data in a vector, like this:

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

The buffering_mem is a function called from NodeJS and should store, individually the information from a few clients (sometimes, the function is called from client 1, sometimes from client 20). But I am getting the error "Unhandled exception...Access violation writing location" in the memcpy. And I am not willing to copy the binary data. Anyone can explain why I am getting this error?

1 个答案:

答案 0 :(得分:1)

执行此代码时:

 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个指向同一内存的对象实例,这很可能不是预期的。

要修复它,可以编写一个合适的复制构造函数。更简单的解决方案是使用向量来管理数据。另外,要减少对象实例化的数量,请使用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);