c++11 - C++ 11 中的单例使用成员函数说明符

标签 c++11 vector singleton

我知道 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/

相关文章:

c++ - 如何将 std::string 转换为 std::vector<uint8_t>?

c++ - 如何在 C++ 中将函数中的 STL 列表作为参数传递

c++ - 将逗号分隔的数据分配给 vector

python - 如何从向量中删除数字?

java - Singleton 在 Spring 中是如何工作的?

c++ - 初始化时的求值顺序

c++ - 我们需要 move 和复制作业吗

c++ - mkdir 系统调用创建权限 0755 而不是 0777

javascript - JQuery addClass 不适用于点击事件上的 anchor 标记

singleton - EJB3 单例 session Bean 和 ConcurrentHashMap