Jeff said:
for me, it
is easier to consider allocations through new to be reserved for instances of
objects, and allocations through malloc to be raw memory.
It is good that you're keeping a conceptual line between raw memory and
typed memory. I don't think avoiding "new" for the raw memory is the
clearest way to express this, though. On the rare occasions when I
really want some raw memory, I typedef unsigned char to a type called
Byte, and work with Bytes as my raw memory. I've found type and
variable names the best places in my code to "self-document."
int main ( )
{
typedef unsigned char Byte;
Byte* raw_memory = new Byte[ 100 ];
// Work with raw memory...
delete [ ] raw_memory;
}
Derived * p = new Derived[15];
Try to explain in simple what p points to, and what you can and can't do w/ the
underlying allocated memory.
p points to the first element in an array of Derived objects.
Contrast that with:
char * c = new char[15];
c points to the first element in an array of char.
Right! Which, conceptually, should be treated differently than an allocated
block of raw memory.
Because Derived is not POD but char is.
Right! I understand that there are special-class types, but feel that it can
be a sticking point for new learners of the language. Personally, I have no
problem w/ it because I stated w/ C and therefore had a basic understanding of
the POD types.
Part of my point is that you have to treat char as a non-POD type AND as an
allocation type for general purpose (raw) memory.
As I've said before, I think of it being more beneficial to think of new as an
allocator of instances of types, and malloc as an allocator of raw (untyped)
memory. My use of malloc is few and far between, so when it does happen, it is
usually very localized or well defined, and I have no problem keeping track of
the allocation scheme.
As I've stated, I would have preferred that new provide a method by which raw
(untyped) memory could be allocated, rather than allocating chars and calling
it raw. I've proposed
void * p = new void[size_in_bytes];
as reasonable candidate for such, although I realize that no such beast will be
making it into the standard, nor is this the forum to discuss such features.