C++:可变函数+私有构造函数漏洞?

问题描述

在练习一些最近学到的功能(可变参数模板等)时,我决定想出不同的方法来创建单例(还记得吗?)。计划了一个非常复杂的想法后,当代码在实施过程中开始工作时,我感到非常惊讶。

我主要关心的是 unbuildable 正在访问 singletonFactory 的(私有)认构造函数。这怎么可能?这是一些未定义的行为吗?编译器错误?纯粹的黑魔法?

#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>()};
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)