by Ragnarork · 7y ago · 0 comments
I have a hard time to get the rationale here. Is the author implying that using memset is inherently better than initializing an std::vector with the constructor that takes a count and a default value, or resetting it with the same variant of .assign()? Skimming through the code that's linked in the article, it looks like there's no use case where either the former or the latter wouldn't fit.
#include <vector>
#include <cstdio>
struct MyFoo {
MyFoo() { printf("default ctor\n"); }
MyFoo(int i) { printf("Initialized with %d\n", i); }
MyFoo(const MyFoo& foo) {}
};
int main() {
std::vector<MyFoo> myvec;
myvec.reserve(100);
printf("resize(2)\n");
myvec.resize(2);
printf("emplace_back()\n");
myvec.emplace_back();
printf("emplace_back(1)\n");
myvec.emplace_back(1);
printf("push_back(MyFoo{1})\n");
myvec.push_back(MyFoo{2});
return 0;
}
It will print: resize(2)
default ctor
default ctor
emplace_back()
default ctor
emplace_back(1)
Initialized with 1
push_back(MyFoo{1})
Initialized with 2
Only the resize() call did a default initialization "silently", nothing else did.