C++栈上和堆上创建对象的区别

本文详细探讨了C++中类对象的静态与动态建立,包括栈和堆的区别,以及new运算符和malloc函数在内存分配中的应用。通过示例代码展示了动态建立对象时如何避免野指针问题,以及使用malloc时对于含有自定义类型成员对象的处理。文章还对比了C++与Java中对象分配的差异,并强调了动态内存管理的重要性。
摘要由CSDN通过智能技术生成

在C++中类的对象建立分为两种,一种是静态建立,如A a;另一种是动态建立,如A* p=new A(),Ap=(A)malloc();静态建立一个类对象,是由编译器为对象在栈空间中分配内存,通过直接移动栈顶指针挪出适当的空间,然后在这片内存空间上调用构造函数形成一个栈对象。动态建立类对象,是使用new运算符将对象建立在堆空间中,在栈中只保留了指向该对象的指针。栈是由编译器自动分配释放 ,存放函数的参数值,局部变量的值,对象的引用地址等。其操作方式类似于数据结构中的栈,通常都是被调用时处于存储空间中,调用完毕立即释放。堆中通常保存程序运行时动态创建的对象,C++堆中存放的对象需要由程序员分配释放,它存在程序运行的整个生命期,直到程序结束由OS释放。而在java中通常类的对象都分配在堆中,对象的回收由虚拟机的GC垃圾回收机制决定。

1.下面的程序来看看静态建立和动态建立对象的区别

#include<iostream>
#include<string>
using namespace std;
class  student
{
public:
    string name;
    int age;
    void sayhello();
};
void student::sayhello()
{
    cout<<"my name is: "+this->name+" I am: "<<this->age;
    cout<<"\n";
}
student setname(string name)
{
    student stu;
    stu.age=12;
    stu.name=name;
    return stu;
}
int main()
{
    student stu=setname("jim");
    stu.sayhello();
    return 0;
}

程序运行结果:my name is: jim I am: 12;

程序定义了一个student类,在setname函数中定义一个局部对象作为返回值。程序第18行静态构建了一个student对象stu,它在栈上分配空间,在函数调用结束后就销毁了,函数返回的类对应在内存中的值应该不存在啊?其实原来C++在用类作为函数的返回值时调用了类的拷贝构造函数,而且该拷贝构造函数是在堆上分配存储空间,后面再讨论这个问题。

在setname函数内的stu在函数调用结束后就销毁了,可以添加一个析构函数来证明:

在student类中加入析构函数:

student::~student()
{
    cout<<this->name<<":gameover"<<endl;
}

程序运行结果:
在这里插入图片描述
在sayhello()前,输出jim:gameover,即为setname()里的stu对象执行了析构函数。

如将setname函数改为:

student* setname(string name)
{
    student stu;
    stu.age=12;
    stu.name=name;
    return &stu;
}

main函数的调用改为:

int main()
{
    student* p=setname("tom");
    p->sayhello();
    return 0;
}

显然这里会出现问题,对象指针返回的是栈上的对象,在函数调用结束后已经销毁了,对象指针即为野指针,故程序在编译时会提示:warning C4172: returning address of local variable or temporary。解决这个问题我们自然想到把该对象构建在堆上即可。修改setname函数为下:

student* setname(string name)
 {
student* stu= new student();
stu->age=12;
stu->name=name;
return  stu;
 }

main函数的调用不变;程序正常运行输出:
在这里插入图片描述
上面输出结果并没有调用析构函数,在setname调用后,在main函数结束后也没有调用。在对上的对象需要程序员自己delete释放,将main改为如下:

int main()
{
    student* p=setname("tom");
    p->sayhello();
    delete p;
    return 0;
}

即加入delete p;运行结果:
在这里插入图片描述

C中用malloc函数来动态申请空间,该内存分配在堆上。这里可以验证,加入#include <malloc.h>,将setname函数改为如下:

student* setname(string name)
 {
student* stu=(student*)malloc(sizeof(student));
stu->age=12;
stu->name=name;
return  stu;
 }

为在student中加入构造函数:

student::student()
{
    cout<<"constructor"<<endl;
}

上面的程序执行会出错,原因是没有调用构造函数,stu->name根本就没有被初始化(string的构造函数没有被调用),所以不能赋值 。具体的解释是: 因为malloc只是分配堆内存(不会调用构造函数)它并不知道内存里要存的是什么。为此用new即可,将代码改为:student* stu=new student;程序运行结果为下:
在这里插入图片描述
即程序调用了构造函数。若非要用malloc来申请内存可以将setname函数改为如下:

student* setname(string name)
 {
student* stu=(student*)malloc(sizeof(student));
new(stu) student;
stu->age=12;
stu->name=name;
return  stu;
 }

即加入了new(stu) student程序正常运行,调用了构造函数。大概可以理解为new了一个student对象,赋值转换为student的指针stu。
既然这样可以把代码直接改为:student* stu;即

student* setname(string name)
 {
//student*stu= new student;
student* stu;
new(stu) student;
stu->age=12;
stu->name=name;
return  stu;
 }

编译程序提示:warning C4700: local variable ‘stu’ used without having been initialized,即stu没有初始化。 new(stu) student;和stu= new student;并不等价。new(stu) student并不是初始化,这里可以看做这种写法(之前还真没见过)是C++为兼容malloc内存申请的用法,一般情况下推荐肯定是用new关键字。到此其实这里要说明的主题已经基本说明了,关于malloc的用法当申请的类的成员变量只包含基本的数据类型(数值型int,double等)(string等引用类除外)时是不会出错的。下面的列子可以证明;

#include<iostream>
#include<string>
#include <malloc.h>
using namespace std;
class course
{
public:
    int id;
    float score;
    void printscore()
    {
    cout<<"id:"<<this->id;
        cout<<" score:"<<this->score<<endl;
    }
};

 course* setscore(int id,float score)
 {
     course* co= (course*)malloc(sizeof(course));
     co->id=id;
     co->score=score;
     return co;
 }
int main()
{
course* cou=setscore(999,188.9);
cou->printscore();
    return 0;
}

程序运行结果如下:
在这里插入图片描述
程序这样的用法没有问题,而之前的string类却有问题。这样看来,自定义类型作为类的成员时也应该会有问题,来看下面的代码:

#include<iostream>
#include<string>
#include <malloc.h>
using namespace std;
class course;
class  student
{
public:
    string  name;
    int age;
        course cou;
    void sayhello();
    ~student();
    student();
};
student::student()
{
    cout<<"constructor"<<endl;
}
student::~student()
{
    cout<<this->name<<":gameover"<<endl;
}
void student::sayhello()
{
    cout<<"my name is: "+this->name+" I am: "<<this->age;
    cout<<"\n";
}
class course
{
public:
    int id;
    float score;
    void printscore()
    {
    cout<<"id:"<<this->id;
        cout<<" score:"<<this->score<<endl;
    }
};
 course* setscore(int id,float score)
 {
     course* co= (course*)malloc(sizeof(course));
     co->id=id;
     co->score=score;
     return co;
 }
 student* setname_score(string name ,course* cou)
 {
student* stu= (student*)malloc(sizeof(student));
stu->age=12;
new(stu)student;
stu->cou.id=cou->id;
stu->cou.score=cou->score;
stu->name= name;
return  stu;
 }
int main()
{
course* cou=setscore(999,188.9);
student* stu=setname_score("jimm",cou);
stu->cou.printscore();
stu->sayhello();
return 0;
}

这段代码中把course类对象作为student的类成员。程序编译出错: error C2079: ‘cou’ uses undefined class ‘course’。把course类的定义放在前面则没有错即:

#include<iostream>
#include<string>
#include <malloc.h>
using namespace std;
class course
{
public:
    int id;
    float score;
    void printscore()
    {
    cout<<"id:"<<this->id;
        cout<<" score:"<<this->score<<endl;
    }
};
class  student
{
public:
    string  name;
    int age;
        course cou;
    void sayhello();
    ~student();
    student();
};
student::student()
{
    cout<<"constructor"<<endl;
}
student::~student()
{
    cout<<this->name<<":gameover"<<endl;
}
void student::sayhello()
{
    cout<<"my name is: "+this->name+" I am: "<<this->age;
    cout<<"\n";
}
course* setscore(int id,float score)
 {
     course* co= (course*)malloc(sizeof(course));
     co->id=id;
     co->score=score;
     return co;
 }
student* setname_score(string name ,course* cou)
 {
student* stu= (student*)malloc(sizeof(student));
stu->age=12;
new(stu)student;
stu->cou.id=cou->id;
stu->cou.score=cou->score;
stu->name= name;
return  stu;
 }
int main()
{
course* cou=setscore(999,188.9);
student* stu=setname_score("jimm",cou);
stu->cou.printscore();
stu->sayhello();
return 0;
}

运行结果为:
在这里插入图片描述
上面程序setname_score函数中若不用new(stu)student;这种写法,则会出现未初始化的错误。这里完全可以将类的成员改为指针的形式,在初始化时用new在堆上分配存储。改写的代码如下:

#include<iostream>
#include<string>
#include <malloc.h>
using namespace std;
class course;
class  student
{
public:
    string*  name;
    int age;
        course* cou;
    void sayhello();
    ~student();
    student();
};
student::student()
{
    cout<<"constructor"<<endl;
}
student::~student()
{
    cout<<this->name<<":gameover"<<endl;
}
void student::sayhello()
{
    cout<<"my name is: "+*(this->name)+" I am: "<<this->age;
    cout<<"\n";
}
class course
{
public:
    int id;
    float score;
    void printscore()
    {
    cout<<"id:"<<this->id;
        cout<<" score:"<<this->score<<endl;
    }
};
course* setscore(int id,float score)
{
     course* co= (course*)malloc(sizeof(course));
     co->id=id;
     co->score=score;
     return co;
}
student* setname_score(string name ,course* cou)
{
student* stu= (student*)malloc(sizeof(student));//student*stu=new student;也一样,只是一个调用构造函数,一个不调用
stu->age=12;
stu->cou=new course();//这里用new建立对象
stu->cou->id=cou->id;
stu->cou->score=cou->score;
stu->name=new string(name);//new
return  stu;
 }
int main()
{
course* cou=setscore(999,188.9);
student* stu=setname_score("jimm",cou);
stu->cou->printscore();
stu->sayhello();
return 0;

}

上面程序运行结果为:
在这里插入图片描述
综上所述,C++中对象的建立可以在堆和栈上。分别为动态建立和动态建立的方式,构建堆上的对象时一般使用new关键字,而对象的指针在栈上。使用new在堆上构建的对象需要主动的delete销毁。C++对象可以在堆或栈中,函数的传参可以是对象(对象的拷贝),或是对象的指针。而在java中对象一般分配在堆上,对象的传值只有值类型,即对象的引用(地址),这样看来C++要灵活的多。关于c++数组的内存分配还有这里提到的拷贝构造函数,下次再讨论啊。上面的程序在VC++6.0编写通过。

  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值