malloc 与 new 区别
- malloc与free 属于库函数new和delete 属于运算符
- malloc不会调用构造函数 new 会调用构造函数
- malloc 返回void * ,c++之下需要进行 强制转换,new 返回创建对象的指针
#include <iostream>
#include <string>
using namespace std;
class Person{
public:
Person(){
cout<<"构造函数调用"<<endl;
}
Person(int a){
cout<<"有参构造函数调用"<<endl;
}
~Person(){
cout<<"Person析构函数调用"<<endl;
}
};
void test01(){
Person * p = new Person;
delete p;
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
利用malloc申请
#include <iostream>
#include <string>
using namespace std;
class Person{
public:
Person(){
cout<<"构造函数调用"<<endl;
}
Person(int a){
cout<<"有参构造函数调用"<<endl;
}
~Person(){
cout<<"Person析构函数调用"<<endl;
}
};
void test01(){
Person *p = (Person *)malloc(sizeof(Person));
free(p);
}
int main(){
test01();
// system("pause");
return EXIT_SUCCESS;
}
不要用void 接受new出来的对象,利用void无法调用析构函数
#include <iostream>
#include <string>
using namespace std;
class Person{
public:
Person(){
cout<<"构造函数调用"<<endl;
}
Person(int a){
cout<<"有参构造函数调用"<<endl;
}
~Person(){
cout<<"Person析构函数调用"<<endl;
}
};
void test01(){
void *p = new Person;
delete p;
}
int main(){
test01();
// system("pause");
return EXIT_SUCCESS;
}
利用new开辟数组,一定调用默认构造函数
#include <iostream>
#include <string>
using namespace std;
class Person{
public:
Person(){
cout<<"构造函数调用"<<endl;
}
Person(int a){
cout<<"有参构造函数调用"<<endl;
}
~Person(){
cout<<"Person析构函数调用"<<endl;
}
};
void test01(){
// 堆区开辟数组,一定调用默认构造函数
Person *pPerson = new Person[10];
delete [] pPerson;
}
int main(){
test01();
// system("pause");
return EXIT_SUCCESS;
}
#include <iostream>
#include <string>
using namespace std;
class Person{
public:
Person(){
cout<<"构造函数调用"<<endl;
}
Person(int a){
cout<<"有参构造函数调用"<<endl;
}
~Person(){
cout<<"Person析构函数调用"<<endl;
}
};
void test01(){
// 堆区开辟数组,一定调用默认构造函数
Person pArray[10] = {
Person(10),
Person(20),
Person(20),
Person(20)
};
}
int main(){
test01();
// system("pause");
return EXIT_SUCCESS;
}