新建和删除运算符重载
new and delete operator overloading
我正在编写一个简单的程序来理解新的和删除运算符重载。如何将size
参数传递到new
运算符中?
作为参考,这是我的代码:
#include<iostream>
#include<stdlib.h>
#include<malloc.h>
using namespace std;
class loc{
private:
int longitude,latitude;
public:
loc(){
longitude = latitude = 0;
}
loc(int lg,int lt){
longitude -= lg;
latitude -= lt;
}
void show(){
cout << "longitude" << endl;
cout << "latitude" << endl;
}
void* operator new(size_t size);
void operator delete(void* p);
void* operator new[](size_t size);
void operator delete[](void* p);
};
void* loc :: operator new(size_t size){
void* p;
cout << "In overloaded new" << endl;
p = malloc(size);
cout << "size :" << size << endl;
if(!p){
bad_alloc ba;
throw ba;
}
return p;
}
void loc :: operator delete(void* p){
cout << "In delete operator" << endl;
free(p);
}
void* loc :: operator new[](size_t size){
void* p;
cout << "In overloaded new[]" << endl;
p = malloc(size);
cout << "size :" << size << endl;
if(!p){
bad_alloc ba;
throw ba;
}
return p;
}
void loc :: operator delete[](void* p){
cout << "In delete operator - array" << endl;
free(p);
}
int main(){
loc *p1,*p2;
int i;
cout << "sizeof(loc)" << sizeof(loc) << endl;
try{
p1 = new loc(10,20);
}
catch (bad_alloc ba){
cout << "Allocation error for p1" << endl;
return 1;
}
try{
p2 = new loc[10];
}
catch(bad_alloc ba){
cout << "Allocation error for p2" << endl;
return 1;
}
p1->show();
for(i = 0;i < 10;i++){
p2[i].show();
}
delete p1;
delete[] p2;
return 0;
}
当你编写一个像 new loc
这样的表达式时,编译器具有静态类型信息,可以让它知道loc
对象有多大。因此,它可以生成将sizeof loc
传递到loc::operator new
的代码。 创建数组时,编译器可以类似地确定容纳数组中所有对象所需的空间量,方法是将数组大小乘以 sizeof loc
,然后还提供一些额外的空间量(以实现定义的方式确定),它将在内部用于存储有关数组中元素数的信息。
希望这有帮助!
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用