Код: Выделить всё
#include
#include
#include
template
void process(void* storage, std::size_t n) {
T* arr = std::launder(reinterpret_cast(storage)); // (4)
// is arr the address of a single object or the address of the existing
// array
// (see usage in main)
for (auto& el : std::span(arr, arr + n)) {
el = T{2};
}
}
int main(int argc, char**) {
std::size_t count = static_cast(10 * argc);
constexpr static std::size_t sz_in_bytes{1000};
// provides storage
alignas(double) std::byte storage[sz_in_bytes]; // (1)
// place an array of double inside storage
auto* darr = ::new (static_cast(storage)) double[count]; // (2)
for (auto& el : std::span(darr, darr + count)) {
el = double{1};
}
// process(storage, count); // an offset might have been introduced at (2)
process(static_cast(darr), count); // (3)
return static_cast(darr[3]);
}
[*] У меня есть некоторое хранилище;
[*] Я помещаю в него массив (из двойного здесь);
Я передаю массив в процесс в качестве указателя к его хранилищу (это может соответствовать схеме эразюры); хочу вернуть указатель на массив двойного для его обработки. std :: raunder ?
Код: Выделить всё
std::start_lifetime_as_array< /code> может быть вариантом, но он не будет работать с некоторыми другими типами (массив должен быть тривиально копируемым). < /p>
Запоздалая мысль: из эмуляции std :: start_lifetime_as_array в c ++ 20 и расслабляя ограничение на trivialliable: < /p>
T* arr = std::launder(reinterpret_cast(std::memmove(storage,storage,sizeof(T)*count));
Подробнее здесь: https://stackoverflow.com/questions/797 ... amic-array