当前位置:网站首页>类如何只能静态分配和只能动态分配
类如何只能静态分配和只能动态分配
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(){
}
};
边栏推荐
- How to drop all tables under database in MySQL
- 一文详解DHCP原理及配置
- C language -- ring buffer
- 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
- 哎,又跟HR在小群吵了一架!
- y86.第四章 Prometheus大厂监控体系及实战 -- prometheus存储(十七)
- 马尔可夫链
- SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropri
- LeetCode每日一题(2285. Maximum Total Importance of Roads)
- 打造一份优雅的简历
猜你喜欢

Functions, recursion and simple dom operations

千兆2光8电管理型工业以太网交换机WEB管理X-Ring一键环网交换机

uni-app 从零开始-基础模版(一)

Dong mingzhu live cold face away, when employees frequency low-level mistakes, no one can understand their products

三分建设,七分管理!产品、系统、组织三管齐下节能降耗

【 observe 】 super fusion: the first mention of "calculate net nine order" evaluation model, build open prosperity of power network

高效IO模型

机器学习模型的“可解释性”

目标检测-中篇

Brush esp8266-01 s firmware steps
随机推荐
sql注入一般流程(附例题)
MySQL查询优化与调优
Deep Learning (3) Classification Theory Part
自制蓝牙手机app控制stm8/stm32/C51板载LED
数据湖(二十):Flink兼容Iceberg目前不足和Iceberg与Hudi对比
docker+bridge+redis master-slave+sentry mode
Exclude_reserved_words 排除关键字
用户与用户互发红包/支付宝C2C/B2C现金红包php源码示例/H5方式/兼容苹果/安卓
ingress 待完善
STM8S105K4T6------串口发送和接收
打造一份优雅的简历
异步编程解决方案 Generator生成器函数、iterator迭代器、async/await、Promise
STM8S-----option byte
FFmpeg —— 录制麦克风声音(附源码)
Good bosses, please ask the flink CDC oracle to Doris, found that the CPU is unusual, a run down
There are n steps in total, and you can go up to 1 or 2 steps each time. How many ways are there?
外卖店优先级
base address: environment variable
The general SQL injection flow (sample attached)
高效IO模型