recently I developed a class header only in C++ to deal with byte arrays. Since I developed programs in other languages that had some libraries to dial with byte arrays, I developed one that the syntax is very similar to other languages.
Since I'm not very familiar with memory management, I was concerned about somethings I've read about (ex: memory fragmentation).
class ByteArray {
public:
ByteArray(size_t size) {
buffer = (int8_t*)malloc(size);
}
~ByteArray() {
free(buffer);
}
//... other functions to insert/retrieve values into/from byte array
private:
int8_t* buffer;
}
int main() {
ByteArray testarray(10);
testarray.writeShort(37231); // insert 2 bytes into byte array
return 0;
}
The class is intended to be used as part of comunication protocol in a webserver, byte arrays are created and destroyed a lot. Should I use pools? Is there a better practice? Am I doing everything wrong (laugh)?
Missing proper copy constructor and assignment operator.
You may use std::vector<int8_t> buffer instead.
> byte arrays are created and destroyed a lot.
> Should I use pools?
I suppose that you could change the allocator used by vector (I have never done it)
However, before that, please analyze if you do need in fact change it.
myesolar, I used that. In this case, what are the practical differences? The only thing I noted is that the std::vector approach is much slower than pointer.
Is there any real difference in this case using new and delete?
he only thing I noted is that the std::vector approach is much slower than pointer.
I doubt that, vector is implemented just as your bytearray is, but more elegantly. If anything you were misusing it, running in debug mode, etc...
Is there any real difference in this case using new and delete?
Yes there is a difference, new int8_t[size] will call the constructor of int8_t for all the indices, which effectively just zeroes out the memory, which is more costly.
> which effectively just zeroes out the memory
¿are you sure?
`int8_t' may be a typedef of a basic type, in which case I thought that you need to write new int8_t[size](); to make them zero.
myesolar, for now I will use new/delete and later I will test a vector version on the server to measure the performance differences in a real scenario.
Thanks, ne555. I used std::copy now, on my tests, it was fully copyed.
Also, it verifies if the assignment is being made with 2 different variables, and initializes a NULL buffer if no size is provided.