当前位置:网站首页>How class only static allocation and dynamic allocation
How class only static allocation and dynamic allocation
2022-08-04 03:36:00 【Can't beat the little ants】
Concept
- Static allocation
The compiler allocates memory in stack space for objects.Using this method, the constructor of the class is called directly.For example:
A a- Dynamic build
Allocate memory in heap space.This process is divided into two steps:
[first step] execute the operator new( ) function to allocate memory in the heap space;
[second step] call the class constructor to construct the object.
Static allocation
Ideas
- To restrict the new operator to implement class objects can only be created on the stack.This restricts the class object from calling the new operator.
class A {private:void* operator new(size_t t){} //Set as privatevoid operator delete(void* ptr){} //If new is overloaded, delete needs to be overloaded.Corresponds to overloading.public:A(){}~A(){}};Dynamic allocation
There are a few points to note.
- Only allowing dynamic allocation requires disallowing direct calls to constructors.But the constructor needs to be called indirectly, so the constructor cannot be made private.
- When the compiler allocates stack space for a class object, it will first check the accessibility of the class's destructor (in fact, not only the destructor, but as long as it is a non-static function, the compiler willan examination).If the class's destructor is not accessible outside the class, the compiler refuses to allocate memory for the class object on stack space.This also disables static allocation.Therefore, destructors can be defined as private.
- Because the destructor is defined as private, an additional destructor needs to be defined to release memory.
class A {public:A(){}void destory(){delete this;}private:~A(){}};边栏推荐
- MRS: Alluxio的使用介绍
- base address: environment variable
- 查看mysql死锁语法
- 函数,递归以及dom简单操作
- 内网服务器访问远程服务器的端口映射
- 2022杭电多校联赛第五场 题解
- 一文看懂推荐系统:召回04:离散特征处理,one-hot编码和embedding特征嵌入
- 基于 SSE 实现服务端消息主动推送解决方案
- Senior PHP development case (1) : use MYSQL statement across the table query cannot export all records of the solution
- 类如何只能静态分配和只能动态分配
猜你喜欢
随机推荐
pnpm 是凭什么对 npm 和 yarn 降维打击的
跨境电商看不到另一面:商家刷单、平台封号、黑灰产牟利
SQL injection in #, - +, - % 20, % 23 is what mean?
Oracle与Postgresql在PLSQL内事务回滚的重大差异
kingbaseES V8R2/R3 表在指定表空间,为何显示为默认表空间?
PHP高级开发案例(1):使用MYSQL语句跨表查询无法导出全部记录的解决方案
Power button (LeetCode) 215. The first K largest elements in the array (2022.08.03)
小程序+新零售,玩转行业新玩法!
The keytool command
Based on the statistical QDirStat Qt directory
if,case,for,while
docker+网桥+redis主从+哨兵模式
MySQL查询优化与调优
《nlp入门+实战:第八章:使用Pytorch实现手写数字识别》
复现20字符短域名绕过
机器学习模型的“可解释性”
Homemade bluetooth mobile app to control stm8/stm32/C51 onboard LED
元宇宙“吹鼓手”Unity:疯狂扩局,悬念犹存
6口全千兆二层网管型工业以太网交换机千兆2光4电光纤自愈ERPS环网交换机
怎么把elastic中的异常登录ip和日志自动导出或抓取到数据库中?






![出现504怎么办?由于服务器更新导致的博客报504错误[详细记录]](/img/e0/32d78fac04dc2deb1cb1f847a7bab5.png)


