Re: dynamically allocated array and vector
"subramanian100in@yahoo.com, India" <subramanian100in@yahoo.com> wrote in
news:b533dd1f-4c04-439e-b7d0-40385058acd4@r27g2000yqn.googlegroups.com:
We have std::vector<T> container for an element type 'T' that
satisfies the element requirements - like Copy Constructible,
Assignable. We also have dynamically allocated arrays. When will we
use std::vector and when will we use dynamically allocated arrays ?
Kindly explain, if possible with sample program.
Normally one should use std::vector. Dynamically allocated arrays are
needed extremely rarely. For example, if one has a large array of
objects, and only some of the objects can contain other small arrays, and
the size of small arrays is known beforehand, or is common to all
objects. In this case one may consider using dynamically allocated arrays
to conserve the overall memory:
#include <vector>
class Object {
public:
Object(): inner_(NULL) {}
~Object() {delete[] inner_;}
void CreateInnerArray() {
inner_ = new int[10]();
}
private:
int* inner_;
};
int main() {
std::vector<Object> large_array(1000000);
// use small inner arrays only for few objects
large_array[17].CreateInnerArray();
large_array[257823].CreateInnerArray();
large_array[856791].CreateInnerArray();
}
When using std::vector inside Object the size of Object and the large
array would explode multiple times. Note that in turn one has to be more
careful in coding, for example here calling CreateInnerArray() multiple
times on the same object would cause memory leaks.
Hope you get the idea - dynamically allocated arrays are useful only in
such artificially constructed examples. Better avoid them.
Paavo