While practicing some recently learned features (variadic templates, etc.) I decided to come up with different ways of creating a singleton (remember those?). Having planned out a very complex idea, I was greatly surprised when the code started working mid-implementation.
My main concern is unbuildable
's (private) default constructor being accessed by singletonFactory
. How is this possible? Is it some undefined behavior? A compiler bug? Unalduterated black magic?
#include <iostream>
template <class C, typename... Args>
auto* singletonFactory(const Args &...params)
{
static auto&& value = (C{params...});
return &value;
};
class unbuildable
{
private:
// This is what makes the black magic work. Defining my own constructor
// breaks the program, even if it takes no arguments. Go figure.
unbuildable() = default;
};
int main()
{
// unbuildable widget; <- Does not compile (obvious)
// Works (but WHY? Isn't the constructor private?)
const auto widget {singletonFactory<unbuildable>()};
}