可以使类名和对象名相同服务于singleton的机制
Can making class name and object name same serve the mechanism of singleton
在下面的代码中,我试图通过使类名和对象名相同来实现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"!
但不用担心,你很可能并不真的需要一个单身汉。
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- C++ Singleton - Prevent ::instance() to variable
- c++r值引用应用于函数指针
- 如果编译的源代码是特定于它编译的硬件的,我们如何分发它
- 如何仅使用对象名称打印特定于对象的成员
- 相当于LocaleMatcher的ICU4C
- 等<thing>效于char32_t
- 类似于strcat()的函数出现问题
- Active Directory:从网络服务帐户下运行的Windows服务调用ADsOpenObject时失败
- 如何将C++闭包与变量参数同时重用——类似于JavaScript
- 算术运算的结果类似于:C浮点变量中的1/3
- 检测win32服务创建和删除的最佳方法
- 使用 mod_gsoap 部署服务时,如何在 Gsoap 中更改 soap 上下文的模式?
- 当服务中的事件被触发时,如何将响应从服务发送回客户端?
- 相当于 pybind11 中的 boost::p ython py::scope().attr()
- 如何将记忆应用于此递归函数?
- QLIST适用于服务
- 使用什么样的API,您可以在OSX中执行read-consistent文件操作,类似于Windows卷影服务
- 可以使类名和对象名相同服务于singleton的机制
- web服务-适用于我的c/c++库的swig、soap或restful