C++ 返回对singleton的常量引用
我试图用一些预定义的方法声明实现一个单例模式。我认为这是可行的,但获得第二个实例会产生另一个实例 我无法更改方法声明或成员变量。我举了一个小例子:C++ 返回对singleton的常量引用,c++,reference,singleton,C++,Reference,Singleton,我试图用一些预定义的方法声明实现一个单例模式。我认为这是可行的,但获得第二个实例会产生另一个实例 我无法更改方法声明或成员变量。我举了一个小例子: #include <iostream> #include <vector> using namespace std; class Singleton { private: Singleton() {}; vector<string> data; static Singleton *
#include <iostream>
#include <vector>
using namespace std;
class Singleton
{
private:
Singleton() {};
vector<string> data;
static Singleton *instance;
public:
static const Singleton &getInstance()
{
if(0 == instance) {
instance = new Singleton;
}
return *instance;
}
void push(string &new_element)
{
data.push_back(new_element);
}
void print()
{
for(vector<string>::iterator it = data.begin(); it != data.end(); ++it) {
cout << *it << endl;
}
}
};
Singleton *Singleton::instance = 0;
int main()
{
Singleton a = Singleton::getInstance();
Singleton b = Singleton::getInstance();
string c1 = "Hello";
string c2 = "World";
a.push(c1);
b.push(c2);
a.print(); // prints only "hello"
}
但这会导致另一个错误:
singleton.cpp:40:45: error: invalid initialization of reference of type ‘Singleton&’ from expression of type ‘const Singleton’
singleton.cpp:41:45: error: invalid initialization of reference of type ‘Singleton&’ from expression of type ‘const Singleton’
为什么会发生这种情况?有人能解释为什么会创建新的单例实例吗
我确实在网上搜索过答案,但没有人像我一样真正使用单例模式。(如果可以的话,我会改变内部结构,但这是一种带有给定代码的作业。)它们需要是
const
参考:
const Singleton &a = Singleton::getInstance();
此代码导致复制Singleton实例:
Singleton a = Singleton::getInstance();
将代码更改为
const Singleton& a = Singleton::getInstance();
这将解决问题。您应该将Singleton的复制构造函数(和赋值运算符)设置为私有,以禁止在编译时复制和赋值:
private:
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
为什么它首先返回一个
const
引用?没有非常量成员函数,所以您不能对其执行任何操作。@MikeSeymour,正如我所说的:这段代码是在不更改它的限制下提供给我的。我知道,这很糟糕。这就是我在这里提问的原因。:-)更改getInstance
以返回非常量引用对我来说似乎更明智。否则,你不能用它做任何事。谢谢。我以前做过,但是我不能再改变它的内容了。那么,这个预先声明被设计破坏了?我的意思是,我需要改变它的值,但考虑到限制,我将不能,除了常量铸造。。。谢谢你的回答!如果单例需要可变(您需要更改其内容),则让getInstance返回一个非常量引用。注意:在C++11中,在方法声明之后使用=delete
,以指定不使用它们。
private:
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);