面试题1:赋值运算符函数
面试题2:实现Singleton模式
赋值运算符函数
//TEST 1赋值运算符重载
class String
{
public:
String(const char* pst =nullptr);
String(const String& pst);
~String();
private:
char * _pst;
};
//赋值运算符重载,释放旧空间,指向创建新空间,数据拷贝。
String& String::operator=(const String& pst)
{
if (this != &pst)
{
delete[] _pst;
_pst == nullptr;
_pst = new char[strlen(pst._pst) + 1];
strcpy(_pst, pst._pst);
}
return *this;
}
实现Singleton模式
//Singleton模式分为两种(懒汉模式,饿汉模式)
//TEST 2 实现一个单例(Singleton)模式
template<class T>
class Singleton_hangry //饿汉模式
{
public:
static T* GetInstance() //静态数据成员获取唯一实例
{
assert(_inst);
return _inst;
}
protected:
Singleton_hangry() //构造函数保护,派生类可见
{};
private:
static T* _inst; //静态成员函数,只能调用静态数据成员
Singleton_hangry(const T&); //拷贝构造和赋值运算符重载定义为私有(防止拷贝)
Singleton_hangry& operator=(const T&);
};
template<class T>
T* Singleton_hangry<T> ::_inst = new T;
//懒汉模式 ,线程安全但是效率不是很高效
template<class T>
class Singleton_lazy
{
public:
static pthread_mutex_t lock;
static T* GetInstance()
{ //两次判空+加锁,为了防止两个线程进入后,造成多次实例化
if (_inst == nullptr)
{
pthread_mutex_lock(&lock);
if (_inst == nullptr)
{
_inst = new T;
}
pthread_mutex_unlock(&lock);
}
return _inst;
}
protected:
Singleton_lazy()
{};
private:
static T* _inst;
Singleton_lazy(const T&);
T& operator=(const T&)
};
template<class T>
T* Singleton_lazy<T>::_inst =nullptr;
template<class T>
pthread_mutex_t Singleton_lazy<T>::lock;