0

The code below compiles, but I am not 100% sure that it conforms to the standard:

#include <memory>

class A
{
public:
    
    int x;
};

int main()
{
    uint8_t m_storage[sizeof(A)];
    
    new (m_storage) A();
    
    auto deleter = [](A * p) { p->~A(); };
    std::unique_ptr<A, decltype(deleter)> p(reinterpret_cast<A *>(m_storage), deleter);
    
    p->x = 0;

    return p->x;
}

Is it a proper usage of reinterpret_cast?

Mat
  • 202,337
  • 40
  • 393
  • 406
Dmitriano
  • 1,878
  • 13
  • 29

1 Answers1

1

Yes it is correct reinterpret cast.

Albeit not correctly aligned storage. And potentially wrong placement new (should cast parameter to void*).

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
  • Looks like it can be `alignas(A) uint8_t m_storage[sizeof(A)];` – Dmitriano Dec 11 '20 at 16:19
  • 1
    Better would be to use [`std::aligned_storage`](https://en.cppreference.com/w/cpp/types/aligned_storage) instead, eg: `std::aligned_storage_t m_storage;` Or, if you need an array of `A`s: `std::aligned_storage_t m_storage[N];` – Remy Lebeau Dec 11 '20 at 18:29