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
  • 195,986
  • 40
  • 382
  • 396
Dmitriano
  • 1,686
  • 11
  • 23

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
  • 10,518
  • 2
  • 31
  • 66
  • 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