杂项
找不到地方放了
new
new
关键字本身并不是现代内容,这里讲的是现代的特性
operator new(operator new[])/operator delete(operator delete[])
分配内存,相当于C中的
malloc
,构造函数不会被调用(不会初始化)
四万字长文说operator new & operator delete
std::string* s1=(std::string*)operator new(sizeof(std::string));//分配内存
std::string* s2=(std::string*)operator new[](sizeof(std::string)*10);//分配内存(数组)
operator delete(s1);//释放内存
operator delete[](s2);//释放内存(数组)
placement new
在用户指定的内存位置上(已经预先分配好的内存)构建新的对象
什么意思?可能有点迷茫?
可以用operator new分配内存,然后用Placement New构造对象(初始化)
int main()
{
std::string* s1 = (std::string*)malloc(sizeof(std::string));
std::string* s2 = new(s1) std::string("hello world");//这里同new operator/delete operator中的构造调用情况
std::cout << *s1 << std::endl;//输出hello world
}
new operator/delete operator
分配内存并初始化
实际上是operator new
和placement new
的结合
std::string* s1=new std::string();//分配内存并调用默认构造
std::string* s1=new std::string("hello world");//有参构造
std::string* s3=new std::string;//分配内存并调用默认构造,但是老版本编译器可能不会调用构造(不会初始化)
delete s1,s2,s3;//释放内存
nullptr
空指针
C中有NULL
,是一个宏定义,通常是0(#define NULL 0
)
NULL
的类型不明确,可能会导致一些问题(比如类型转换)
//一种NULL会出错的情况
void NumOrPointer(int a){
std::cout<<"int"<<std::endl;
}
void NumOrPointer(int* a){
std::cout<<"pointer"<<std::endl;
}
int main(){
NumOrPointer(NULL);//输出int
NumOrPointer(nullptr);//输出pointer
return 0;
}
nullptr
可以被转换为任何指针类型,而且不会被转换为整型(nullptr
的类型是nullptr_t
)
所以在表示空指针的时候尽量使用nullptr
而非NULL