我有C++类,表示一个可以存储的缓冲区。
unsigned char
Segmentation fault (core dumped)
memcpy
如果我改用
std::copy(value, value, _valueChar);
我还有其他错误:
error: no type named âvalue_typeâ in âstruct std::iterator_traits<int>â
#include <iostream>
#include <cstring>
#include <utility>
#include <vector>
#include <string>
class SkinnyBuffer {
private:
unsigned char *_valueChar;
std::size_t _sizeChar;
public:
SkinnyBuffer();
SkinnyBuffer(std::size_t size);
~SkinnyBuffer();
void clean();
template<typename T>
void addValue(T value) {
if (_valueChar != nullptr) {
delete[] _valueChar;
}
// _sizeChar = n; // assume _size is a field
// _valueChar = new unsigned char[_sizeChar];
// std::copy(value, value, _valueChar);
memcpy(_valueChar, &value, sizeof(value));
}
template<typename T>
void addValue(std::size_t offset, T value) {
if (_valueChar != nullptr) {
delete[] _valueChar;
}
// _sizeChar = n; // assume _size is a field
// _valueChar = new unsigned char[_sizeChar];
// std::copy(value, value + offset, _valueChar);
memcpy(_valueChar + offset, &value, sizeof(value));
}
unsigned char *getValue() {
return _valueChar;
}
};
#include "SkinnyBuffer.h"
SkinnyBuffer::SkinnyBuffer() {
}
SkinnyBuffer::SkinnyBuffer(std::size_t size) {
_sizeChar = size;
_valueChar = new unsigned char[_sizeChar];
}
SkinnyBuffer::~SkinnyBuffer() {
}
void SkinnyBuffer::clean() {
_valueChar = new unsigned char[_sizeChar];
}
int main(int argc, char *argv[]) {
int value = 50;
int offset = sizeof(value);
SkinnyBuffer b(offset);
b.addValue(value);
int dValue;
memcpy(&dValue, b.getValue(), offset);
std::cout << dValue << std::endl;
}