辛格尔顿,但有一个扭曲的公共建筑商

发布于 2025-02-02 16:11:56 字数 461 浏览 0 评论 0原文

最近,我在代码评论中遇到了类似的事情。

/* 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文