#include <array>
#include <iostream>
#include <memory>
const size_t N = 5;
struct A
{
int x;
A(int x) : x(x) { std::cout << "Created" << std::endl; }
A(const A& rhs) : x(rhs.x) { std::cout << "Copied" << std::endl; }
~A() { std::cout << "Destroyed" << std::endl; }
};
int makeElement(size_t i)
{
return i * i;
}
struct Deleter
{
Deleter() {};
void operator()(std::array<A, N>* p) const
{
for (auto& item : *p) { item.~A(); }
std::return_temporary_buffer(p);
};
};
std::unique_ptr<std::array<A, N>, Deleter> makeArrayDynamically()
{
A* buf;
std::tie(buf, std::ignore) = std::get_temporary_buffer<A>(N);
for (size_t i = 0; i < N; ++i)
{
new (buf + i) A(makeElement(i)); // Yeah, I will have a leak if some constructor throws
}
return { reinterpret_cast<std::array<A, N>*>(buf), Deleter() };
}
int main()
{
const auto pArr = makeArrayDynamically();
for (const auto& item : *pArr)
{
std::cout << item.x << std::endl;
}
}
I2luY2x1ZGUgPGFycmF5PgojaW5jbHVkZSA8aW9zdHJlYW0+CiNpbmNsdWRlIDxtZW1vcnk+Cgpjb25zdCBzaXplX3QgTiA9IDU7CgpzdHJ1Y3QgQQp7CiAgaW50IHg7CiAgQShpbnQgeCkgOiB4KHgpIHsgc3RkOjpjb3V0IDw8ICJDcmVhdGVkIiA8PCBzdGQ6OmVuZGw7IH0KICBBKGNvbnN0IEEmIHJocykgOiB4KHJocy54KSB7IHN0ZDo6Y291dCA8PCAiQ29waWVkIiA8PCBzdGQ6OmVuZGw7IH0KICB+QSgpIHsgc3RkOjpjb3V0IDw8ICJEZXN0cm95ZWQiIDw8IHN0ZDo6ZW5kbDsgfQp9OwoKaW50IG1ha2VFbGVtZW50KHNpemVfdCBpKQp7CiAgcmV0dXJuIGkgKiBpOwp9CgpzdHJ1Y3QgRGVsZXRlciAKewogIERlbGV0ZXIoKSB7fTsKICB2b2lkIG9wZXJhdG9yKCkoc3RkOjphcnJheTxBLCBOPiogcCkgY29uc3QgCiAgeyAKICAgIGZvciAoYXV0byYgaXRlbSA6ICpwKSB7I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