用智能指针管理,可以使单例模式调用析构函数
#include <iostream>
#include <memory>
using namespace std;
class Singleton
{
public:
static Singleton* GetInstance()
{
/*if (instacne_ == NULL)
{
instacne_ = new Singleton;
}
return instacne_;*/
if (!instance_.get())//获得裸指针
{
instance_ = auto_ptr<Singleton>(new Singleton);
}
return instance_.get();//返回原生指针,但是还保留所有权
}
~Singleton()
{
cout<<"~Singleton ..."<<endl;
}
private:
Singleton(const Singleton& other);//禁止拷贝
Singleton& operator=(const Singleton& other);
//将构造函数声明为私有
Singleton()
{
cout<<"Singleton ..."<<endl;
}
static auto_ptr<Singleton> instance_;
};
auto_ptr<Singleton> Singleton::instance_;
int main(void)
{
//Singleton s1;
//Singleton s2;
Singleton* s1 = Singleton::GetInstance();
Singleton* s2 = Singleton::GetInstance();
//Singleton s3(*s1); // 调用拷贝构造函数
return 0;
}
#include<iostream>
using namespace std;
//两指针相减,得到的是相隔几个元素
#define sizeof_v(x) (char*)(&x+1) -(char*)(&x)
#define sizeof_t(t) ((size_t)((t*)0+1))
//对齐
#define ALIGN(v,b) ((v+b-1) & ~(b-1))
class Empty
{
};
int main(void)
{
Empty e;
int n;
cout << sizeof_v(n) << endl;
cout << sizeof_t(Empty) << endl;
cout << ALIGN(3, 16) << endl;
cout << ALIGN(31, 16) << endl;
return 0;
}