Re: Best way to allocate memory for simple types and objects
Dmytro Bablinyuk wrote:
I came across several possible ways of allocating memory for objects,
for example:
1. malloc(sizeof(T)*3)/free - raw memory
2. new T[3]/delete[] - buffer would be initialized to
default-constructed T objects.
3. operator new(sizeof(T)*3)/operator delete - raw memory
What the best way of allocating memory for simple types and objects?
For a single object: new T/delete T (and you can specify any
parameters you want for the initializer of T).
For an array of objects:
std::vector< T > array( ... ) ;
To initialize all of them with a default value:
std::vector< T > array( n ) ; // n is the dimension...
To initialize them from a static array:
std::vector< T > array( start, finish ) ;
For objects the "new T[3]" looks like the best way since it
initializes the array, but what about simple types?
How are simple types different from anything lese?
There's almost never a reason to use the array form of
new---std::vector does the job much better. As to the other
forms, they return a void*, and should only be used when you
want raw memory, i.e. when you separate allocation and
construction.
Right now for "int *" I am using malloc, but would it be
better if I use "operator new" for instance? What the
advantages?
Type safety, to begin with. Use std::vector, and you'll not
have to worry about the delete, either.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]