可以使类名和对象名相同服务于singleton的机制

Can making class name and object name same serve the mechanism of singleton

本文关键字:服务于 singleton 机制 对象 可以使      更新时间:2023-10-16

在下面的代码中,我试图通过使类名和对象名相同来实现singleton(即具有单个对象的类)的目的。

以下代码中是否存在任何缺陷,以达到singleton类的目的?

#include <iostream>
using namespace std;
class singleton
{
    private :
        int val;
    public : 
        void set(int a)
        {
            val=a;
        }
        int display()
        {
            return val;
        }
} singleton;

int main()
{
    singleton.set(5);
    cout << "output a = " <<singleton.display()<< endl; 
    //singleton obj;//second object will not be allowed
    return 0;
}

您的类型不是singleton,因为您可以创建任意数量的实例

auto cpy = singleton;
cpy.set(42);
assert(singleton.display() != cpy.display());
// let's make loads of copies!
std::vector<decltype(singleton)> v(100, cpy); // 100 "singletons"!

但不用担心,你很可能并不真的需要一个单身汉。