Re: Two C++ questions
Julie wrote:
[color=blue]
> 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.[/color]
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;
}
[color=blue]
> 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.[/color]
p points to the first element in an array of Derived objects.
[color=blue]
> Contrast that with:
>
> char * c = new char[15];[/color]
c points to the first element in an array of char.
[color=blue]
> and why you can treat it differently.[/color]
Because Derived is not POD but char is.
Julie wrote:
[color=blue]
> 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.[/color]
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;
}
[color=blue]
> 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.[/color]
p points to the first element in an array of Derived objects.
[color=blue]
> Contrast that with:
>
> char * c = new char[15];[/color]
c points to the first element in an array of char.
[color=blue]
> and why you can treat it differently.[/color]
Because Derived is not POD but char is.
Comment