On 1/26/2016 7:26 PM, Victor Bazarov wrote:
> On 1/26/2016 1:24 PM, Bill Cunningham wrote:
>> I just wanted to ask someone famailiar with C++ this question. just
>> asked this nextdoor in clc so I will get clc++'s take. In C one
>> initializes
>> a dynamic array as such,
>>
>> int *p;
>> p=malloc(10*sizeof(int));
>>
>> And this works for its' purpose. How is dynamic memory handled in C++?
>> In an
>> easier manner?
>
> Ease is in the eye of the beholder. In C++ it is done either exactly
> the same way (since 'malloc' is part of C++ just as it is part of C),
Well in C++ one has to cast the result of `malloc` unless a `void*` is
what one desires, while in C one shouldn't cast the result lest one
inadvertently generates an implicit declaration when the relevant
include is missing. This difference in the advice or best practice for
the two languages is due to different rules for implicit conversions,
and different rules for implicit declarations. Of course, using `malloc`
is usually not best practice in C++ anyway, but it can be necessary due
to requirements of C APIs, or for use of `realloc`.
> or
>
> int *p = new int[10];
Yes.
One difference here is that this defaults to throwing an exception when
memory can't be allocated, while malloc returns a nullpointer, so at
least when memory exhaustion is an issue one can't just replace a C
`malloc` call with a C++ `new` expression and have equivalent C++ code.
• • •
All those differences noted, I think in C++ one should generally prefer
standard library containers when possible, and in this case, just use
`vector<int>`,
vector<int> v( 10 );
which automates all that memory management, is more robust, and provides
much useful & convenient functionality.
I'm pretty sure you agree with that but just didn't put that in your
short & fast answer.
Cheers,
- Alf