c++ 用new后delete,而继续输出指针后果

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  

 

因为这里实参是通过传值方式传递的,会用默认构造函数创建实参的副本,副本的指针跟实参的指针指向空闲存储器中同一个字符串。 超出函数作用域后,副本会析构,使副本里 的指针 指向的内存被释放。  但实参还是指着那个位置,所以可能出错。 

posted @ 2017-05-28 11:12 ff_d 阅读( ...) 评论( ...) 编辑 收藏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值