When instances of classes derived from the same class need to be created based on certain conditions, they are created on the heap. The puzzle is about how to do it on the stack.
Stack Factory Puzzle
By Alex Marmer
March 18-23, Tokyo, Japan
April 17-20, Bristol, UK
April 24-26, Leganes, Spain
April 30, Online
May 7-12, Aspen, CO, USA
June 24-29, St. Louis, MO, USA
July 2-5, Folkestone, Kent, UK
By Alex Marmer | Sep 11, 2018 01:41 PM | Tags: None
When instances of classes derived from the same class need to be created based on certain conditions, they are created on the heap. The puzzle is about how to do it on the stack.
Stack Factory Puzzle
By Alex Marmer
Bertin Colpron said on Sep 12, 2018 05:14 AM:
std::variant<int,X0,X1,X2> x;
if (i == 0) {
x.emplace<X0>();
pX = &std::get<X0>(x);
} else if (i == 1) {
x.emplace<X1>();
pX = &std::get<X1>(x);
} else {
x.emplace<X2>();
pX = &std::get<X2>(x);
}
Emanrov E. Emanhcan said on Sep 12, 2018 02:58 PM:
// Begin
constexpr auto size = std::max(
alignof(X0) - 1 + sizeof(X0),
std::max(
alignof(X1) - 1 + sizeof(X1),
alignof(X2) - 1 + sizeof(X2)
)
);
char memory[size];
if (i == 0) {
void* ptr = memory;
auto space = size;
pX = new (std::align(alignof(X0), sizeof(X0), ptr, space)) X0;
}
else if (i == 1) {
void* ptr = memory;
auto space = size;
pX = new (std::align(alignof(X1), sizeof(X1), ptr, space)) X1;
}
else {
void* ptr = memory;
auto space = size;
pX = new (std::align(alignof(X2), sizeof(X2), ptr, space)) X2;
}
std::unique_ptr<X, void (*)(X*)> x{
pX,
[](X* ptr) { ptr->~X(); }
};
// End
Dennis Börm said on Sep 12, 2018 09:55 PM:
Dennis Börm said on Sep 13, 2018 12:02 AM:
Add a Comment