以下程序旨在实例化和使用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;
}
Thx,Keith:^)
答案 0 :(得分:2)
你的问题是你正在初始化里面的计数器
<块引用>getInstance() 方法
相反,在构造函数中初始化它 您的代码应如下所示,
#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() {counter =0;}
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;
s->getInstance().increment(); // increment counter
std::cout << t->getInstance().getCtr() << std::endl;
s->getInstance().increment(); // increment counter
std::cout << t->getInstance().getCtr() << std::endl;
s->getInstance().increment(); // increment counter
std::cout << t->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;
}
那么输出将是
0
1
2
3
4
5
Press any key to exit...