当前位置:网站首页>类如何只能静态分配和只能动态分配
类如何只能静态分配和只能动态分配
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(){
}
};
边栏推荐
- Utilities of Ruineng Micrometer Chip RN2026
- 十一种概率分布
- QNX Hypervisor 2.2 user manual] 10.1 gm vdev options
- 【指针内功修炼】深度剖析指针笔试题(三)
- 基地址:环境变量
- 逻辑漏洞----其他类型
- [Study Notes Dish Dog Learning C] Dynamic Memory Management
- C language -- ring buffer
- SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropri
- In a more general sense, calculating the displacement distance and assumptions
猜你喜欢
SQL injection in #, - +, - % 20, % 23 is what mean?

自定义通用分页标签02

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

【医保科普】维护医保基金安全,我们可以这样做

打造一份优雅的简历

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

一文详解DHCP原理及配置

Sfdp 超级表单开发平台 V6.0.5 正式发布

仿牛客论坛项目梳理

Dong mingzhu live cold face away, when employees frequency low-level mistakes, no one can understand their products
随机推荐
base address: environment variable
MySQL 查询练习(1)
全网没有之一的JMeter 接口测试流程详解
基于Qt的目录统计QDirStat
什么是数字孪生智慧城市应用场景
Ant - the design of the Select component using a custom icon (suffixIcon attribute) suffixes, click on the custom ICONS have no reaction, will not display the drop-down menu
缓存穿透、缓存击穿、缓存雪崩以及解决方案
[Playwright Test Tutorial] 5 minutes to get started
案例 | 重庆银行流动数据安全挑战及应对实践
返回字符串中的最大回文数
kingbaseES V8R2/R3 表在指定表空间,为何显示为默认表空间?
小程序+新零售,玩转行业新玩法!
WPE详细教程
架构实战营模块三作业
uni-app 从零开始-基础模版(一)
[Original] Start the XPS/OXPS reader that comes with Windows 10
多线程间的通信方式你知道几种?
Mockito单元测试
力扣(LeetCode)215. 数组中的第K个最大元素(2022.08.03)
高效IO模型