Look up "zero copying" for the protocol part.
The problem you have is that your pointer is actually a nullptr
at the time you are trying to use it. You need to check the return from malloc
:
Buffer::Buffer() :
buffer_(reinterpret_cast<int*>(malloc(bufferSize*nBuffers)))
{
if(buffer_ == nullptr) throw std::bad_alloc();
}
But, you should use new
instead which would do this check and throw bad_alloc
automatically if it fails:
Buffer::Buffer() :
buffer_(new int[bufferSize*nBuffers])
{
// no need to check here
}
For every malloc
you need one free
, and for every new
you need one delete
- and you should never mix them.
Also, malloc
allocates bytes, but an int
is usually 4 or 8 bytes so you'd need to multiply the number of int
s you want to allocate space for with sizeof(int)*CHAR_BIT/8
to get the correct size.
Just forget about malloc
and free
and use new
and delete
in their place.
This is how you delete your array allocated with new int[...]
:
Buffer::~Buffer() {
delete[] buffer_; // delete array
}
An even better option is to use a std_unique_ptr
which will do the delete[]
for you when it goes out of scope:
class Buffer {
private:
std::unique_ptr<int[]> buffer_;
public:
Buffer() :
buffer_(std::make_unique<int[]>(bufferSize * nBuffers))
{}
// ~Buffer() no need to implement a destructor unless you manually handle resources
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…