------/malloc与new区别
5 10
Test()
7756144 0
~Test
malloc和free是库函数,以字节为单位申请堆内存
new和delete是关键字,以类型为单位申请堆内存
malloc和free单纯对内存进行申请与释放
对于基本类型new关键字可进行初始化
对于类类型new和delete还负责构造函数和析构函数的调用
------/
C++编译器会尝试各种手段让程序通过编译
方式一:尽力匹配重载函数
方式二:尽力使用函数的默认参数
方式三:尽力尝试调用构造函数进行类型转换
Test t1= 5古代编译器编译过程分析:
1默认情况,字面量5类型为int,无法直接初始化Test对象
2但编译器默认情况可自动调用构造函数
3于是编译器尝试主动调用Test(int)生成一临时对象
4之后调用拷贝构造函数Test(const Test&)用临时对象对t2进行初始化
等价于Test t1 = Test(Test(5));导致效率低下
Test(int i)
Test(int i)
Test(int i)
~Test
~Test
~Test
没打印Test(const Test& obj),因现代编译器进行优化
------/
explicit关键字用于剥夺编译器对构造函数的调用尝试
给Test(int i)或Test(const Test& obj)任意一个加explicit均导致Test t2 = 5错误
给Test(const Test& obj)加explicit导致Test t3 = Test(5)错误
均加explicit不会导致Test t1(5)错误,因其为标准初始化写法,程序员明确指明要调用
------/单例模式
对象数目控制,一个类最多有一个对象存在于系统中
new Singleton()
0x305970 0x305970 0x305970
class Test
{
private:
int i;
public:
Test()
{
cout<<"Test()"<<endl;
i = 0;
}
Test(int i)
{
cout<<"Test(int i)"<<endl;
this->i = i;
}
~Test()
{
cout<<"~Test"<<endl;
}
int getI()
{
return i;
}
};
int main()
{
int* p = reinterpret_cast<int*>(malloc(sizeof(int)));
int* q = new int; //等价int*q=new int(10);
*q = 10;
*p = 5;
cout<<*p<<" "<<*q<<endl;
free(p);
delete q;
Test* op = reinterpret_cast<Test*>(malloc(sizeof(Test))); //非对象,单纯的内存
Test* oq = new Test;
cout<<op->getI()<<" "<<oq->getI()<<endl;
free(op);
delete oq;
return EXIT_SUCCESS;
}
结果:
5 10
Test()
7756144 0
~Test
malloc和free是库函数,以字节为单位申请堆内存
new和delete是关键字,以类型为单位申请堆内存
malloc和free单纯对内存进行申请与释放
对于基本类型new关键字可进行初始化
对于类类型new和delete还负责构造函数和析构函数的调用
------/
C++编译器会尝试各种手段让程序通过编译
方式一:尽力匹配重载函数
方式二:尽力使用函数的默认参数
方式三:尽力尝试调用构造函数进行类型转换
Test t1= 5古代编译器编译过程分析:
1默认情况,字面量5类型为int,无法直接初始化Test对象
2但编译器默认情况可自动调用构造函数
3于是编译器尝试主动调用Test(int)生成一临时对象
4之后调用拷贝构造函数Test(const Test&)用临时对象对t2进行初始化
等价于Test t1 = Test(Test(5));导致效率低下
class Test
{
public:
Test(int i)
{
cout<<"Test(int i)"<<endl;
}
Test(const Test& obj)
{
cout<<"Test(const Test& obj)"<<endl;
}
~Test()
{
cout<<"~Test"<<endl;
}
};
int main(int argc, char *argv[])
{
Test t1(5);
Test t2 = 5;
Test t3 = Test(5);
return EXIT_SUCCESS;
}
结果:
Test(int i)
Test(int i)
Test(int i)
~Test
~Test
~Test
没打印Test(const Test& obj),因现代编译器进行优化
------/
explicit关键字用于剥夺编译器对构造函数的调用尝试
给Test(int i)或Test(const Test& obj)任意一个加explicit均导致Test t2 = 5错误
给Test(const Test& obj)加explicit导致Test t3 = Test(5)错误
均加explicit不会导致Test t1(5)错误,因其为标准初始化写法,程序员明确指明要调用
------/单例模式
对象数目控制,一个类最多有一个对象存在于系统中
class Singleton
{
private:
static Singleton* cInstance;
Singleton() //*****
{
}
public:
static Singleton* GetInstance() //静态方法只能访问静态成员
{
if( cInstance == NULL )
{
cout<<"new Singleton()"<<endl;
cInstance = new Singleton();
}
return cInstance;
}
};
Singleton* Singleton::cInstance = NULL;
int main(int argc, char *argv[])
{
Singleton* s0 = Singleton::GetInstance();
Singleton* s1 = Singleton::GetInstance();
Singleton* s2 = Singleton::GetInstance();
cout<<s0<<" "<<s1<<" "<<s2<<endl;
return EXIT_SUCCESS;
}
结果:
new Singleton()
0x305970 0x305970 0x305970