C++ 11-私人构造函数仍然可呼叫
我在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
函数之前创建了类。
我必须提出问题:
- 为什么在私有时,在第二个变体中调用
ctor
? - 为什么
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:
- Why the
ctor
is called in the second variant while being private? - Why the
dtor
's access rights are different in the first variant?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
welp,我还没有找到标准的确切措辞,但是 IBM网站的此页面说:
,因此似乎扩大了类的范围。
此页面在cppreference.com上说,类范围扩展到“ 课堂内括号或平等初始化”,所以可能就是这样。
Welp, I haven't found the exact wording of the standard, but this page of IBM site says that:
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.