C++中用new和不用new创建类对象最本质区别:
(1)作用域不同:
不用new:作用域限制在定义类对象的方法中,当方法结束时,类对象也被系统释放了。(安全不会造成内存泄露)
用new:创建的是指向类对象的指针,作用域编程了全局,当程序结束时,必须用delete 来删除,系统不会自动释放。(不注意可能造成内存泄露)
(2)一个类对象,一个指向类对象的指针
- // newtest.cpp : Defines the entry point for the console application.
- //
-
- #include "stdafx.h"
- #include <stdio.h>
- #include <vld.h>//メモリリーク調査用
- class Person
- {
- private:
- char* pName;
-
- public:
- Person(char* pName){
- this->pName = pName;
- printf("[%s] is constructed.\n", this->pName);
- }
-
- ~Person(){
- printf("[%s] is deconstructed.\n", this->pName);
- }
- };
-
- void* Fun(){
-
- //Zhangsan是临时类对象,Fun函数返回時,Zhangsan被释放。
- Person Zhangsan("Zhangsan");
- //pList是临时类指针,pList变量被释放,pList指向地址未被释放。(Lisi没有被释放)
- Person *pLisi = new Person("Lisi");
- return pLisi;
- }
- int main(int argc, char* argv[])
- {
- printf("----------Fun begin ...\n");
- Person * pLisi = (Person*)Fun();
- printf("----------Fun end.\n");
- delete pLisi;//释放Lisireturn 0;
- }
结果:
- ----------Fun begin ...
- [Zhangsan] is constructed.
- [Lisi] is constructed.
- [Zhangsan] is deconstructed.
- ----------Fun end.
- [Lisi] is deconstructed.
- Press any key to continue
C#中用new和不用new创建对象最本质区别:
C#要实例化一个类,必须使用new;若果不用new无法创建类对象。
我也是刚开始学习C#,对于说的不正确的地方请大家指正。
|