65,211
社区成员
发帖
与我相关
我的任务
分享
//只在栈上
class stackonly
{
private:
void * operator new(size_t Size)
{
}
};
//只在堆上
class heaponly
{
private:
heaponly(){}
~heaponly(){}
};
//HeapOnly.cpp
#include <iostream>
using namespace std;
class HeapOnly
{
public:
HeapOnly() { cout << "constructor." << endl; }
void destroy () const { delete this; }
private:
~HeapOnly() {}
};
int main()
{
HeapOnly *p = new HeapOnly;
p->destroy();
// HeapOnly h;
// h.Output();
return 0;
}
//StackOnly.cpp
//2005.07.18------2009.06.05
#include <iostream>
using namespace std;
class StackOnly
{
public:
StackOnly() { cout << "constructor." << endl; }
~StackOnly() { cout << "destructor." << endl; }
private:
void* operator new (size_t);
};
int main()
{
StackOnly s; //okay
StackOnly *p = new StackOnly; //wrong
return 0;
}
只在栈上的类:
// 私有重载new即可,但只是限制了不能建立在new出的堆上,并没有限制全局以及局部静态类,因此严格
// 来说不能算“只在栈上”
class A
{
private:
static void *operator new (size_t size){};
};只在堆上的类:
// 私有化析构函数,通过一个public函数来进行实际的析构。
class B
{
public:
void del()const{ };
private:
~B(){};
};