, , , char* A*: , A* A* , , .
- :
#include <new>
#include <iostream>
struct A
{
int t;
};
char *buf = new char[sizeof(A)];
A* ptr = new (buf) A;
ptr->t = 1;
A *ptr2 = reinterpret_cast<A*>(buf);
std::cout << ptr2->t;
( , , !).
. . , , placement- new , char.
( ++ 11) std::aligned_storage :
using Storage = std::aligned_storage<sizeof(A), alignof(A)>::type;
auto* ptr = new Storage;
, , :
Storage data;
placement- :
new (ptr) A();
:
*reinterpret_cast<A*>(ptr);
:
#include <iostream>
#include <new>
#include <type_traits>
struct A
{
int t;
};
int main()
{
using Storage = std::aligned_storage<sizeof(A), alignof(A)>::type;
auto* buf = new Storage;
A* ptr = new(buf) A();
ptr->t = 1;
A* ptr2 = reinterpret_cast<A*>(buf);
std::cout << ptr2->t;
}
( )
, ++ 17, ; . cppreference std::launder.
, , A , , ; , A , buf , - , .