当前位置:网站首页>类如何只能静态分配和只能动态分配
类如何只能静态分配和只能动态分配
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(){
}
};
边栏推荐
- TOML configuration file format, YAML's top contender
- 数据集类型转换—TFRecords文件
- Polygon zkEVM network node
- 安装postgis时报找不到“POSTGIS_VERSION”这个函数
- Big guys, it takes a long time to read mysql3 million single tables, what parameters can be discounted, or is there any way to hurry up
- base address: environment variable
- 一文看懂推荐系统:召回05:矩阵补充、最近邻查找,工业界基本不用了,但是有助于理解双塔模型
- Utilities of Ruineng Micrometer Chip RN2026
- [Playwright Test Tutorial] 5 minutes to get started
- Based on the statistical QDirStat Qt directory
猜你喜欢

【观察】超聚变:首提“算网九阶”评估模型,共建开放繁荣的算力网络

《nlp入门+实战:第八章:使用Pytorch实现手写数字识别》

高效IO模型

【Playwright测试教程】5分钟上手

6-port full Gigabit Layer 2 network managed industrial Ethernet switch Gigabit 2 optical 4 electrical fiber self-healing ERPS ring network switch

How to drop all tables under database in MySQL

STM8S105K4T6------串口发送和接收

马尔可夫链

Countdown to 2 days, the "New Infrastructure of Cultural Digital Strategy and Ecological Construction of Cultural Art Chain" will kick off soon

Based on the statistical QDirStat Qt directory
随机推荐
db2中kettle报错 Field [XXX] is required and couldn‘t be found 解决方法
How to read the resources files in the directory path?
哎,又跟HR在小群吵了一架!
怎样提高网络数据安全性
Utilities of Ruineng Micrometer Chip RN2026
2 Gigabit Optical + 6 Gigabit Electric Rail Type Managed Industrial Ethernet Switch Supports X-Ring Redundant Ring One-key Ring Switch
"Introduction to nlp + actual combat: Chapter 8: Using Pytorch to realize handwritten digit recognition"
[QNX Hypervisor 2.2 User Manual] 10.3 vdev gic
pytorch applied to MNIST handwritten font recognition
脚手架内容详解分析
There are n steps in total, and you can go up to 1 or 2 steps each time. How many ways are there?
单片机C语言->的用法,和意思
Rongyun "Audio and Video Architecture Practice" technical session [complete PPT included]
Deep Learning (3) Classification Theory Part
QNX Hypervisor 2.2 user manual] 10.1 gm vdev options
仿牛客论坛项目梳理
Mockito单元测试
自定义通用分页标签01
SQL injection in #, - +, - % 20, % 23 is what mean?
FFmpeg —— 录制麦克风声音(附源码)