当前位置:网站首页>类如何只能静态分配和只能动态分配
类如何只能静态分配和只能动态分配
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(){
}
};
边栏推荐
- 一个属于程序员的七夕节!
- SQL injection in #, - +, - % 20, % 23 is what mean?
- Innovation and Integration | Huaqiu Empowerment Helps OpenHarmony Ecological Hardware Development and Landing
- [QNX Hypervisor 2.2 User Manual] 10.3 vdev gic
- 初识Numpy
- 【指针内功修炼】深度剖析指针笔试题(三)
- 如何在MySQL中的数据库下删除所有的表
- 基本表单验证流程
- 一文看懂推荐系统:召回04:离散特征处理,one-hot编码和embedding特征嵌入
- QNX Hypervisor 2.2 user manual] 10.1 gm vdev options
猜你喜欢
STM8S105k4t6c--------------点亮LED
Dong mingzhu live cold face away, when employees frequency low-level mistakes, no one can understand their products
什么是数字孪生智慧城市应用场景
学会iframe并用其解决跨域问题
tkmapper的crud示例:
"Introduction to nlp + actual combat: Chapter 8: Using Pytorch to realize handwritten digit recognition"
【项目实现】Boost搜索引擎
Architecture of the actual combat camp module three operations
In a more general sense, calculating the displacement distance and assumptions
Pine脚本 | 如何显示和排版绘图开关?
随机推荐
[Original] Start the XPS/OXPS reader that comes with Windows 10
SQL injection in #, - +, - % 20, % 23 is what mean?
如果禁用了安全启动,GNOME 就会发出警告
Returns the maximum number of palindromes in a string
如何在MySQL中的数据库下删除所有的表
QNX Hypervisor 2.2 user manual] 10.1 gm vdev options
基于Qt的目录统计QDirStat
Asynchronous programming solution Generator generator function, iterator iterator, async/await, Promise
MRS: Introduction to the use of Alluxio
跨境电商看不到另一面:商家刷单、平台封号、黑灰产牟利
脚手架内容详解分析
【 observe 】 super fusion: the first mention of "calculate net nine order" evaluation model, build open prosperity of power network
new Date将字符串转化成日期格式 兼容IE,ie8如何通过new Date将字符串转化成日期格式,js中如何进行字符串替换, replace() 方法详解
Utilities of Ruineng Micrometer Chip RN2026
【项目实现】Boost搜索引擎
Hey, I had another fight with HR in the small group!
基地址:环境变量
STM8S-----option byte
FPGA解析B码----连载3
初识Numpy