c++ - Is it not possible to construct instances in a loop without a pointer? -
this code explode, right? loop exits, original instances die inner members if weren't pods, method do_stuff
requires access members of b
throw segmentation fault, correct?
void foo() { std::vector<b> bar; (int = 0; < 7; i++) bar.push_back(b(i, i, i)); bar[3].do_stuff(); }
so, there way without using pointer? or have this:
void foo() { std::vector<b*> bar; (int = 0; < 7; i++) bar.push_back(new b(i, i, i)); bar[3]->do_stuff(); (int = 0; < 7; i++) delete bar[i]; }
the first code better second one.
the b
instances movedsince c++11/copiedpre-c++11 vector, not fall out of scope after loop — after vector falls out of scope.
if want absolutely optimal performance, this:
void foo() { std::vector<b> bar; bar.reserve(7); (int = 0; < 7; i++) bar.emplace_back(i, i, i); bar[3].do_stuff(); }
this guarantee 1 reallocation, , elements constructed directly inside vector (instead of moving or copying them there) per marc glisse's comments.
Comments
Post a Comment