C++ 11-私人构造函数仍然可呼叫

发布于 2025-02-05 23:12:01 字数 1057 浏览 3 评论 0原文

我在mainloop.h中对类的以下定义有所定义:

class MainLoop {
    private:
        static const MainLoop     &s_instance;
    public:
        static inline const MainLoop &Instance(void) 
            { return s_instance; }
  
    private:
        MainLoop(MainLoop &mp);
        MainLoop(MainLoop &&mp);
        MainLoop &operator=(MainLoop &mp);
        MainLoop &operator=(MainLoop &&mp);
        ~MainLoop();
        MainLoop()
            { printf("Main Loop is created\n"); };
};

并且在源文件mainloop.cpp中有点像:

#include "MainLoop.h"

const MainLoop &MainLoop::s_instance( (MainLoop()) );

此代码不编译,因为> dtor是范围中的私有,但是如果我将其更改为异想天开

#include "MainLoop.h"

const MainLoop &MainLoop::s_instance( *( new MainLoop()) );

,然后在不说单词的情况下编译,并且在调用main函数之前创建了类。

我必须提出问题:

  1. 为什么在私有时,在第二个变体中调用ctor
  2. 为什么dtor的访问权限在第一个变体中有所不同?

I have somewhat the following definition of a class in MainLoop.h:

class MainLoop {
    private:
        static const MainLoop     &s_instance;
    public:
        static inline const MainLoop &Instance(void) 
            { return s_instance; }
  
    private:
        MainLoop(MainLoop &mp);
        MainLoop(MainLoop &&mp);
        MainLoop &operator=(MainLoop &mp);
        MainLoop &operator=(MainLoop &&mp);
        ~MainLoop();
        MainLoop()
            { printf("Main Loop is created\n"); };
};

And somewhat like that in the source file MainLoop.cpp:

#include "MainLoop.h"

const MainLoop &MainLoop::s_instance( (MainLoop()) );

This code does not compile because the dtor is private in the scope, but if I change it to the whimsical

#include "MainLoop.h"

const MainLoop &MainLoop::s_instance( *( new MainLoop()) );

it then compiles without saying a word and the class is created before the main function is called.

I have to questions:

  1. Why the ctor is called in the second variant while being private?
  2. Why the dtor's access rights are different in the first variant?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请爱~陌生人 2025-02-12 23:12:01

welp,我还没有找到标准的确切措辞,但是 IBM网站的此页面说:

静态数据成员的初始化器处于宣布成员的类范围

,因此似乎扩大了类的范围。

此页面在cppreference.com上说,类范围扩展到“ 课堂内括号或平等初始化”,所以可能就是这样。

Welp, I haven't found the exact wording of the standard, but this page of IBM site says that:

The initializer for a static data member is in the scope of the class declaring the member

So, it seems like the scope of the class is extended.

This page at cppreference.com says that class scope is extended to "in-class brace-or-equal initializers", so probably this is it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文