c++ 用new后delete,而继续输出指针后果
1 #include<iostream> 2 #include<cstring> 3 #include <string.h> 4 5 int main(){ 6 7 int *a =new int[100]; 8 for(int i=0;i<100;i++){a[i]=i;} 9 char *b; 10 delete []a; 11 for(int i=0;i<1000000;i++){ 12 b=new char [100]; 13 b="dfdf";} 14 15 for(int i=0;i<100;i++){cout<<a[i]<<endl;} 16 cout<<endl<<a; 17 18 }
所以不要这样
1 #include<iostream> 2 #include<cstring> 3 #include <string.h> 4 using namespace std; 5 class Cbox{ 6 char * aa; 7 public: 8 int g ; 9 Cbox(const char *a){int length =(strlen(a)+1); 10 aa= new char[length +1]; 11 strcpy(aa,a); 12 cout<<"gouzao"<<endl;} 13 Cbox()=default; 14 ~Cbox(){delete aa;cout<<"xigou"<<endl;} 15 void show(){cout<<aa<<endl;} 16 }; 17 18 void display (Cbox a){ 19 a.show();} 20 21 22 23 24 int main(){ 25 char as[100]="""asd1200"; 26 Cbox a(as) ; 27 28 display(a); 29 a.show(); 30 } 31
因为这里实参是通过传值方式传递的,会用默认构造函数创建实参的副本,副本的指针跟实参的指针指向空闲存储器中同一个字符串。 超出函数作用域后,副本会析构,使副本里 的指针 指向的内存被释放。 但实参还是指着那个位置,所以可能出错。