如何解决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 举报,一经查实,本站将立刻删除。