当前位置:网站首页>类如何只能静态分配和只能动态分配
类如何只能静态分配和只能动态分配
2022-08-04 03:11:00 【打不倒小蚂蚁】
概念
- 静态分配
编译器为对象在栈空间中分配内存。使用这种方法,是直接调用类的构造函数。举个例子:
A a
- 动态建立
堆空间中分配内存。这个过程分为两步:
【第一步】执行operator new( )函数,在堆空间中进行内存分配;
【第二步】调用类的构造函数构造对象。
静态分配
思路
- 要限制new运算符就可以实现类对象只能建立在栈上。这样就可以限制类对象调用new运算符。
class A {
private:
void* operator new(size_t t){
} //设置为私有
void operator delete(void* ptr){
} //重载了new就需要重载delete。对应重载。
public:
A(){
}
~A(){
}
};
动态分配
有以几点需要注意。
- 仅允许动态分配需要禁止直接调用构造函数。但是需要间接调用构造函数,因此不能将构造函数设为private。
- 编译器在为类对象分配栈空间时,会先检查类的析构函数的访问性(其实不光是析构函数,只要是非静态的函数,编译器都会进行检查)。如果类的析构函数在类外部无法访问,则编译器拒绝在栈空间上为类对象分配内存。这样也就禁止了静态分配。因此,可以将析构函数定义为私有。
- 由于将析构函数定义为私有,需要额外定义析构函数释放内存。
class A {
public:
A(){
}
void destory(){
delete this;}
private:
~A(){
}
};
边栏推荐
猜你喜欢
随机推荐
用户与用户互发红包/支付宝C2C/B2C现金红包php源码示例/H5方式/兼容苹果/安卓
Pine Script | How to display and typeset a plot switch?
Functions, recursion and simple dom operations
There are too many systems, how to realize multi-account interworking?
6口全千兆二层网管型工业以太网交换机千兆2光4电光纤自愈ERPS环网交换机
Pine脚本 | 如何显示和排版绘图开关?
Asynchronous programming solution Generator generator function, iterator iterator, async/await, Promise
【医保科普】维护医保基金安全,我们可以这样做
SQL注入中 #、 --+、 --%20、 %23是什么意思?
4-way two-way HDMI integrated business high-definition video optical transceiver 8-way HDMI high-definition video optical transceiver
STM8S项目创建(STVD创建)---使用 COSMIC 创建 C 语言项目
外卖店优先级
tkmapper的crud示例:
小程序+新零售,玩转行业新玩法!
STM8S-----option byte
pnpm 是凭什么对 npm 和 yarn 降维打击的
数组相关 内容 解析
Hey, I had another fight with HR in the small group!
目标检测-中篇
[Medical Insurance Science] To maintain the safety of medical insurance funds, we can do this









