zr said:
Allen schrieb:
There is a custom STL in place allocator in Google codes.
The InPlaceAlloc.h URL ishttp://
www.google.com/codesearch/p?hl=en#HClD5fLW7P8/InPlaceAlloc.h&q...
#include <vector>
#include "InPlaceAlloc.h"
int main()
{
char * buffer = new char[1024];
Avoid new[]. Avoid delete[]. Except buried down in a class or library.
You can use std::vector to allocate a buffer:
std::vector<char> buffer(1024);
Why is using a vector to allocate better than using new[]
and delete []?
In general, because it lessens the risk of memory leaks. With
new[], you have to delete[] in every possible code path, which
can be quite complicated in some functions, especially if you
allocate multiple arrays. It is very hard to make it
exception safe. Most people don't even try it and ignore that
issue. With std::vector or any other smart-pointer or RAII
construct, the objects will be destroyed even then.
That's true, but not really relevant here. Similarly, a much
more important reason for using std::vector is that in any
decent implementation, the operator[] will be bounds checked,
and the type in general behaves like a normal type, with value
semantics. And that the type carries its dimensions along with
it.
None of which are really relevant here, because the user isn't
allocating an array, in the classical sense, he's allocating raw
memory. And the problem with new char[] is that it says the
wrong thing; it says that he is allocating an array of char. I
know, the language allows an array of char to be used as raw
memory. But that doesn't mean that you can't write code which
says what you mean. In this case, I'd call the :
perator new
function directly, e.g.:
void* buffer = :
perator new( quantityNeeded ) ;
// ...
:
perator delete( buffer ) ;
(I'd also maintain the pointer as a void* where ever possible,
since this is the conventional type for a pointer to raw
memory.)
With regards to his original code:
1. I'd also ensure that the allocator took not only a pointer,
but also the size, and verify that constantly. (Part of his
problem, at least, is that the array he's allocating isn't
big enough.)
2. I'd define some memory management strategy. The simplest,
here, is just to use the Boehm collector; another solution
I've found useful in many cases is to pass an additional
boolean argument to the client, telling it whether to delete
in the destructor or not---since allocator must support
copy, this would require some tricky reference counting
here. Or... Just a guess, but it wouldn't surprise me if in
all of the actual use cases for this class, the memory
doesn't really have to be deleted anyway. (But if he'd
posted code without the delete, a lot of people would have
screamed about that.)