1

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>()};
}
Talmid
  • 15
  • 5
  • Here's an unrelated tip you were interested you in. All that `mystery` related stuff does not appear to be relevant to what's asked here. All extra material should be removed from code shown on Stackoverflow. – Sam Varshavchik Apr 15 '21 at 22:46
  • Edited. Thanks, @SamVarshavchik. – Talmid Apr 15 '21 at 22:48
  • Replace `unbuildable widget;` (the version that doesn't work) with `unbuildable widget{};` and it works. I haven't figured out why. – Woodford Apr 15 '21 at 23:43
  • setting `-std=c++20` flag for clang/gcc will result in the expected error while `-std=c++17` or below does not – Sekkmer Apr 15 '21 at 23:55
  • Is this relevant? http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1507 – Paul Sanders Apr 16 '21 at 00:23

0 Answers0