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 11-13, Online
March 16-18, Madrid, Spain
March 23-28, Croydon, London, UK
March 30, Kortrijk, Belgium
May 4-8, Aspen, CO, USA
May 4-8, Toronto, Canada
June 8 to 13, Brno, Czechia
June 17-20, Folkestone, UK
September 12-18, Aurora, CO, USA
November 6-8, Berlin, Germany
November 16-21, Búzios, Rio De Janeiro, Brazil
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