我知道 issues with the Singleton Pattern ,但我想通过练习使用 C++11 成员函数说明符创建单例来了解 C++11。
无论如何,我做到了这一点:
#include<new>
#include<vector>
class Singleton
{
private:
Singleton() = default;
~Singleton() = default;
public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
void* operator new(std::size_t) = delete;
void* operator new[](std::size_t) = delete;
void operator delete(void*) = delete;
void operator delete[](void*) = delete;
static const Singleton& getInstance()
{
static Singleton mySingleton;
return mySingleton;
}
};
int main(int argc, const char *argv[])
{
const Singleton& s1 = Singleton::getInstance();
// Why does this compile?
std::vector<Singleton> v1;
// Or this?
std::vector<Singleton> v2(50);
return 0;
}
我的问题是,为什么这些行:
std::vector<Singleton> v1;
std::vector<Singleton> v2(50);
编译,而不是报告默认 Singleton 构造函数在私有(private)上下文中的错误?
我在 64 位 Linux 机器上使用 gcc 4.8.2,代码编译为 here也是。
最佳答案
您的代码不使用 getInstance 之外的 Singleton 的默认构造函数,因为向量是空的。
关于c++11 - C++ 11 中的单例使用成员函数说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21231925/