Java和C++在堆栈中创建对象的简单对比

来源:互联网 发布:淘宝客服工作室照片 编辑:程序博客网 时间:2024/05/01 06:25

最近写java的项目,由于对java不熟悉,即使是一个简单的错误和bug都要调试很久,因此只有不断总结才能更加深刻的认识。

出现错误的代码是这样的:

List<File> filelist = null;filelist.clear();
报的错误是:java.lang.NullPointerException;这应该就是一个空指针的错误,现在想想应该不合理,但是之前调试还是花了一些功夫。

那么我写了一段小的Java代码来进行调试:

import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class Factory {public static void main(String [] args){//ArrayList list = null;//error. because no memory space is allocated for the space where list point.List list = new ArrayList();//yeslist.add(1);list.add(2);list.add(3);Iterator it = list.iterator();while(it.hasNext()){Integer n = (int) it.next();System.out.println(n);}}}
ArrayList  list只是定义了一个list对象,但是并没有为其分配空间,在Java中要通过new为对象分配空间,而new分配的空间是在堆(heap)中。但是对比一下C++中类似数组容器的使用:

#include<iostream>#include<vector>using namespace std;int main(){    vector<int> vec;    vec.push_back(1);    vec.push_back(2);    vec.push_back(3);    for(int i=0;i<vec.size();i++)        cout<<vec[i]<<endl;    system("pause");    return 0;}
由于对语言特性理解的不深刻,我就存在疑问,为什么vector<int> vec;没有使用new分配空间但是仍然可以进行push_back添加操作呢?那是因为vector是一个类模板,那么在创建对象vec的时候,会自动调用vector类的构造函数,构造函数中分配了空间,赋予vec堆中的地址。

而C++中用类去声明一个对象时是什么样的情况呢?

class Point{};main(){    Point p;       Point *q;    q = new Point();}
p会自动调用Point中的默认构造函数,在栈中分配对象的内存空间;而q是一个指针类型,用new在堆中为其所指内容分配了内存空间。


下面附上一段代码来简单的理解一下:

#include<iostream>#include<vector>#include<string>#include<stdlib.h>using namespace std;class PointClass{private:int x;int y;public:PointClass(){cout<<"this is default constructor"<<endl;}PointClass(int a,int b){cout<<"this is the constructor with reference"<<endl;x = a;y = b;}void set(int a,int b){x = a;y = b;}void get(){cout<<"The value => "<<x<<" "<<y<<endl;cout<<"The locations => "<<&x<<" "<<&y<<endl<<endl;}};typedef struct PointStruct{PointStruct(){cout<<"this is the point struct  constructor"<<endl;}int x;int y;}tPointStruct;int main(){int *p;p = (int *)malloc(sizeof(int));cout<<"The location of p => "<<&p<<endl;//指针p在栈中的地址 cout<<"The value of p =>"<<p<<endl<<endl;//指针p的内容,也就是p所指向的堆中的地址 vector<int> v;cout<<"The location of v => "<<&v<<endl;//v在栈中的地址 v.push_back(1);cout<<"The location of v[0] => "<<&v[0]<<endl;//可以从结果看出v[0]在堆中 cout<<"The value of v[0] => "<<v[0]<<endl<<endl;tPointStruct *ps; ps = new PointStruct();ps->x =1;cout<<"the location of ps->x ==>"<<&(ps->x)<<endl<<endl;tPointStruct ps0;ps0.x = 1;cout<<"the location of ps.x ==>"<<&(ps0.x)<<endl<<endl;    PointClass* pcfun();//事实上,这是一个函数的定义         PointClass pc0;//在栈中创建对象     pc0.get();    PointClass pc(1,2);//在栈中创建对象     pc.get();        PointClass *pc1;    pc1 = new PointClass(3,4);//在堆中创建对象     pc1->get();        PointClass *pc2;    pc2 = pcfun();//调用函数返回指针指向堆中的对象     pc2->get();    system("pause") ;return 0;}PointClass* pcfun(){    PointClass *p = new PointClass();    p->set(5,6) ;    return p;}

运行结果:

从结果中看出堆在高地址,栈在低地址。







原创粉丝点击