Re: Why using the new keyword at all for memory allocation?
On May 23, 8:28 pm, PencoOdS...@gmail.com wrote:
Why using the new keyword at all for memory allocation?
I mean,why not let c++ find memory for you variable automatically?
so insted of :
int proba;
proba = new int[5];
why not just :
int proba[5];
????????????
Lifetime.
First, of course, you'd never write the former; it won't even
compile. There are cases where the second might be used, when
you know the exact size of the array, and it is a compile time
constant, but something like:
std::vector< int > proba( 5 ) ;
is much more frequent and useful. (And I can't think of a case
where you'd ever use "new int[5]".)
But both the first and the second have automatic storage
duration if they are declared as local variables, and static
storage duration if they are declared at namespace scope (or if
you add the specifier "static" before the declaration of a local
variable). Automatic storage duration follows scope; the
variable ceases to exist when you leave the scope in which it
was defined. And static storage duration is the lifetime of the
program. If this doesn't match the requirements, you have to
manage lifetime yourself, manually, which means new and delete,
e.g.:
std::vector< int >* proba = NULL ;
// ...
proba = new std::vector< int >( 5 ) ;
// ...
delete proba ;
While this occurs very, very rarely for more or less basic
types, like int or vector, it is the usual case for entity
objects.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34