“构造类静态局部变量”的“构造类”是什么意思?

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/07 09:18:31

“构造类静态局部变量”的“构造类”是什么意思?
“构造类静态局部变量”的“构造类”是什么意思?

“构造类静态局部变量”的“构造类”是什么意思?
eyers在effective c++中提到过,他建议采用函数内部静态变量来解决; 即所有的全局变量之间都采用函数来代替直接访问对象,如object.f() -> object().f();
下例是单例模式的应用
class Singleton
{
public:
// 公开方法
void method1()
{
cout << "call 1" << endl;
}
void method2()
{
cout << "call 2" << endl;
}
// 访问
static Singleton& getInstance()
{
static Singleton cs_object('p1',"p2");
return cs_object;
}
public:
// 其他访问
static Singleton& getAnotherInstance()
{
static Singleton cs_object("no-user");
return cs_object;
}
// 需要多个对象
template<int iIndex>
static Singleton& getKthInstance()
{
static Singleton cs_object("kth-object");
return cs_object;
}
private:
// 禁止创建
Singleton(int,const char*)
{
cout << "first construct" << endl;
}
Singleton(const char*)
{
cout << "first construct" << endl;
}
// 禁止删除
Singleton()
{
cout << "last construct" << endl;
}
// 禁止拷贝
Singleton(const Singleton&);
Singleton& operator = (const Singleton&);
};
class Customer1
{
public:
Customer1(const Singleton& s)
{
cout << "customer1 visit" << endl;
}
};
// 全局变量访问
Customer1 g_cstm1(Singleton::getInstance());
class Customer2
{
public:
Customer2(const Singleton& s)
{
cout << "customer2 visit" << endl;
}
Customer2()
{
Singleton::getInstance();
cout << "customer2 visit" << endl;
}
};
int main()
{
// 局部变量访问
Customer2 cstm2(Singleton::getInstance());
}
另,以上方法存在线程安全问题
可以使用智能指针+双重校验来改进
比如
// 针对每一个类提供一个单例访问点; 如果从不访问,则不会创建多余对象
template<typename T>
T& getInstance()
{
static std::auto_ptr<T> ls_object;
if (ls_object.get() == NULL)
{
Guard grd(SingletonHelper<T>::cs_mtx);
if (ls_object.get() == NULL)
{
ls_object.reset(T::createInstance());
}
}
return *ls_object;
}
另外,在
Andrei Alexandrescu的Loki中也有很强大的实现可以借鉴