辛格尔顿,但有一个扭曲的公共建筑商
最近,我在代码评论中遇到了类似的事情。
/* A.h */
class A {
enum Priv {
k1,
};
public:
A(Priv);
static A& getInstance();
};
而且...
/* A.cpp */
A::A(Priv) {}
/* static */
A& A::getInstance() {
static auto instance = A(Priv::k1);
return instance;
}
事情有效,但是为什么要使用a
的公共构造函数,这是从班级以外的任何组件中都无法调用的,而不仅仅是将构造函数私有化(如常态) ?我想知道这种样式比通常的私人构造函数(如果有)会带来什么样的额外好处?
I recently came across something similar in my code reviews.
/* A.h */
class A {
enum Priv {
k1,
};
public:
A(Priv);
static A& getInstance();
};
and...
/* A.cpp */
A::A(Priv) {}
/* static */
A& A::getInstance() {
static auto instance = A(Priv::k1);
return instance;
}
Things work, but why go the stretch of having a public constructor for A
which can never be invoked from any component outside the class rather than just make the constructor private (as is the norm)? I would like to know what kind of extra benefit does this style endow over the usual private constructor style (if any)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论