Using std::launder to retrieve a dynamic array

1 day ago 1
ARTICLE AD BOX

The following answered so question gives me doubts about the way to retrieve, from a storage, a dynamic array constructed inside this storage.

The linked question explains how to do that for a static-sized array but not for a dynamic-sized one. The problem for dynamic array is evoked here but the issue is bypassed by returning only the address of the elements, not the array.

Here is a snippet to illustrate:

#include <cstddef> #include <memory> #include <stdexcept> #include <new> bool is_aligned_to(void* ptr, std::size_t alignment) noexcept { void* p{ptr}; std::size_t sz{1}; return (std::align(alignment, sz, p, sz) == ptr); } void MakeDouble(void* location,std::size_t n) { if (!is_aligned_to(location, alignof(double))) { throw std::invalid_argument("bad alignment"); } new (location) double[n]; } int main(int argc, const char**) { static constexpr std::size_t N = 1000 * sizeof(double); std::byte static_storage[N]; MakeDouble(static_storage,10); [[maybe_unused]] double *arr = std::launder(reinterpret_cast<double *>(static_storage)); }

LIVE

Is std::launder(reinterpret_cast<double *>(static_storage)); enough to retrieve a real array (in the sense that pointer arithmetic is valid) or does it returns the address of a single element?

Is the answer the same if I do:

void MakeDouble(void* location, std::size_t n) { if (!is_aligned_to(location, alignof(double))) { throw std::invalid_argument("bad alignment"); } for (size_t i = 0;i<n;++i) { std::construct_at(reinterpret_cast<double *>(location)+i,3.14); } }

LIVE

Where I don't make explicitly an array but build contiguous objects of same type?

Read Entire Article