c++ - on storage class whereabout -
let's have vector takes struct point
type, see snippet below. function adds 2 points it. since points here locally initialized. there issue/concern points not accessible when function returns? there copy
action happening inside vector container, if so, these data struct stored? in heap?
struct point { int x; int y; string name; }; vector<point> pointvec; int addpoints() { point p1 {2, 3, "point 1"}; point p2 {4, 4, "point 2"}; pointvec.push_back(p1); pointvec.push_back(p2); }
vector
starts no memory allocated. during first push_back
, allocates enough room 1 element , copies passed point in. during next push_back
, reallocates enough room both elements, , moves copy of previous element new memory copies second point. if push_back
again, allocate enough room (typically) 4 elements, move copies, , copy new one.
there standardized restrictions (amortized constancy) on complexity of these operations require allocated vector memory grow proportionally vectors current length. reason must grow proportionally because of moves existing elements (like second push_back
described above). means complexity of reallocation grows length of vector, , amortized constant insertions no longer amortized constant. counteract that, reallocation must proportional length. proportionality typically 2x current length, though don't believe required be.
the memory in example allocated on heap, if provide different allocator type vector, allocated anywhere allocator allows.
so, example safe, slow, , typically requires 2 allocations on heap simple function. better solution preallocate necessary memory using reserve
method allocates heap memory once.
int addpoints() { point p1 {2, 3, "point 1"}; point p2 {4, 4, "point 2"}; pointvec.reserve(2); pointvec.push_back(p1); pointvec.push_back(p2); }
Comments
Post a Comment