【发布时间】:2017-04-27 18:04:58
【问题描述】:
以下程序旨在实例化和使用 Loki Astari 提出的单例模式类,并在以下链接中被接受为答案。 C++ Singleton design pattern
注意通过私有counter 变量以及increment() mutator 和getCtr() 访问器方法添加了一个简单的计数器。
预期的程序输出是:
0
1
Press any key to exit...
实际输出是
0
0
Press any key to exit...
为什么单例类中的计数器没有按预期递增?
下面是一个最小的、完整的、可验证的程序,用于说明问题。
#include "stdafx.h"
#include <iostream>
#include <string>
class S {
public:
static S & getInstance() {
static S instance;
instance.counter = 0; // initialize counter to 0
return instance;
}
S(S const &) = delete;
void operator = (S const &) = delete;
void increment() { ++counter; }
int getCtr() { return counter; }
private:
S() {}
int counter;
};
int main() {
S * s; // s is a pointer to the singleton object
S * t; // t is another pointer to the singleton object.
std::cout << s->getInstance().getCtr() << std::endl;
s->getInstance().increment(); // increment counter
std::cout << t->getInstance().getCtr() << std::endl;
std::cout << "Press any key to exit...";
std::cin.get();
return 0;
}
谢谢,基思 :^)
【问题讨论】:
-
因为您的 getInstance() 每次调用时都会将值设置为零?
-
如何正确初始化这个值为0?
-
您在构造函数中将其初始化为在创建对象时需要初始化的任何其他值。
-
每次需要访问对象时是否需要调用
getInstance()方法,还是有更简单的方法?
标签: class c++11 object singleton instance