分享

创建类对象时:用new和不用new区别!

 520jefferson 2015-05-07

C++中用new和不用new创建类对象最本质区别:

 

(1)作用域不同:

不用new:作用域限制在定义类对象的方法中,当方法结束时,类对象也被系统释放了。(安全不会造成内存泄露)

用new:创建的是指向类对象的指针,作用域编程了全局,当程序结束时,必须用delete 来删除,系统不会自动释放。(不注意可能造成内存泄露)

(2)一个类对象,一个指向类对象的指针

 


  1. // newtest.cpp : Defines the entry point for the console application.  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include <stdio.h>  
  6. #include <vld.h>//メモリリーク調査用  
  7. class Person  
  8. {  
  9. private:  
  10.     char* pName;  
  11.       
  12. public:  
  13.     Person(char* pName){  
  14.         this->pName = pName;  
  15.         printf("[%s] is constructed.\n", this->pName);  
  16.     }  
  17.   
  18.     ~Person(){  
  19.         printf("[%s] is deconstructed.\n", this->pName);  
  20.     }  
  21. };  
  22.   
  23. void* Fun(){  
  24.           
  25.     //Zhangsan是临时类对象,Fun函数返回時,Zhangsan被释放。  
  26.     Person Zhangsan("Zhangsan");   
  27.     //pList是临时类指针,pList变量被释放,pList指向地址未被释放。(Lisi没有被释放)  
  28.     Person *pLisi = new Person("Lisi");  
  29.     return pLisi;  
  30. }  
  31. int main(int argc, char* argv[])  
  32. {  
  33.     printf("----------Fun begin ...\n");  
  34.     Person * pLisi = (Person*)Fun();  
  35.     printf("----------Fun end.\n");  
  36.     delete  pLisi;//释放Lisireturn 0;  
  37. }  


结果:

  1. ----------Fun begin ...  
  2. [Zhangsan] is constructed.  
  3. [Lisi] is constructed.  
  4. [Zhangsan] is deconstructed.  
  5. ----------Fun end.  
  6. [Lisi] is deconstructed.  
  7. Press any key to continue  


 


 

C#中用new和不用new创建对象最本质区别:

C#要实例化一个类,必须使用new;若果不用new无法创建类对象。

 

 

 

我也是刚开始学习C#,对于说的不正确的地方请大家指正。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多