文章目录
- 0 概述
- 1 Primitives
- 1.1 new expression
- 1.2 delete expression
- 1.3 调用构造函数与析构函数
- 1.4 array new & array delete
0 概述
- C++应用程序
- malloc非常重要
0.1 四个层面的基本用法
- 使用一下这四个层面
- 层面1和层面2都是很常见的内存管理分配方法
- 看看层面3,其实和层面1也就是malloc差不多,其实这个
::operator new()
这个语句底层服务就是malloc()
提供的,下方的delete()
底层是free()
- 对于
- 关于层面4,以下是几个层面的分配器使用
- 使用分配器要记得拿了几个,到时候归还的时候就要还多少个
#ifdef _MSC_VERint* p4 = allocator<int>().allocate(3, (int*)0); allocator<int>().deallocate(p4,3);
#endif
#ifdef __BORLANDC__int* p4 = allocator<int>().allocate(5); allocator<int>().deallocate(p4,5);
#ifdef __GNUC__void* p4 = allocator<int>().allocate(7); allocator<int>().deallocate((int*)p4,7); void* p5 = __gnu_cxx::__pool_alloc<int>().allocate(9); __gnu_cxx::__pool_alloc<int>().deallocate((int*)p5,9);
#endif
- 在GNUC当中,放的是字节
- 以上就是对四个层面的Primitives做的一个示范
1 Primitives
1.1 new expression
- new后面需要加上class name
- new会做什么动作?会分配一块内存,准备放object,分配好后自动调用构造函数,当然自动被调用不是被new调用
- new做两个动作,分配内存+调用构造函数
new Complex(1, 2)
使用C++标准语言实现- 注意
operator new()
那一句就是进行空间的分配,这个底层就是malloc static_cast
就是做一个指针的转型- 之后需要调用构造函数
Complex::Complex(1, 2)
这个就是调用构造函数
- 注意看
operator new
的底层,如果默认的new不行,会调用newh
用户自己设定的函数,如果这边malloc失败就会来调用你设定的那个newh
函数 - 在自己设定的
newh
释放内存之后,以便重新调用malloc - 当山穷水尽的时候,内存用完了,就会调用你设定的函数
newh
以便释放内存然后重新malloc
1.2 delete expression
- delete会先调用析构函数,执行完毕,对象内存会被释放
1.3 调用构造函数与析构函数
- 问题1:为什么是
class std::basic_string
而不是string
?因为string只是一个typedef,所以真正的还是basic_string
#include <iostream>
#include <string>
namespace jj02
{class A
{
public:int id;A() : id(0) { cout << "default ctor. this=" << this << " id=" << id << endl; }A(int i) : id(i) { cout << "ctor. this=" << this << " id=" << id << endl; }~A() { cout << "dtor. this=" << this << " id=" << id << endl; }
};void test_call_ctor_directly()
{cout << "\ntest_call_ctor_directly().......... \n"; string* pstr = new string;cout << "str= " << *pstr << endl;
cout << "str= " << *pstr << endl;A* pA = new A(1); cout << pA->id << endl;
cout << pA->id << endl; delete pA;
- 可以看出这个是在VC6当中是可以调用构造函数的,但是在其他编译器当中不行
cout << pA->id << endl; delete pA;
- 欲想直接调用构造函数,可使用
placement new: new (p)Complex (1,2);
1.4 array new & array delete
1.4.1 array new
- 顾名思义,就是一次性建造一整个array的对象
Complex*pca = new Complex[3];
delete[]
注意看后面的方框,如果没有后面的方框,就只会调用一次的析构- 加上了[]就说明会调用三次的析构