I'm "modernizing" a (pretty old) C++ project, and stumbling on this part:
The old code allocates memory for a dynamic array, then call constructor later for element if needed. I guess calling constructor for all elements is expensive, so the author chose to do this way (performance is critical for this project). The old code looks like this (simplified):
struct my_struct {
my_struct(int x, int y, int z) { /* expensive ctor */ }
};
struct other_class {
my_struct* arr;
other_class(int n) {
arr = (my_struct*) malloc(n * sizeof(arr[0]);
}
void foo(int idx, int a, int b, int c) {
new (&arr[idx]) my_struct(a, b, c);
}
};
I changed arr to std::vector<my_struct>, and use std::reserve to "reserve" the memory. The code works okay, pass all current tests, but I know it's not okay, since std::reserve doesn't increase the size of that vector, so calling arr.size() will still return 0. Here's my code:
struct other_class {
std::vector<my_struct> arr;
other_class(int n) {
arr.reserve(n);
}
void foo(int idx, int a, int b, int c) {
new (&arr[idx]) my_struct(a, b, c);
}
};
How to make this code fast and safe (assuming that I can't add a default ctor to my_struct)? Thank you.
Edit: here's the sample code. It is compiled and run as expected, without any warnings: http://cpp.sh/8ytwf