c++中构造函数产生的对象在函数的栈区还是堆区

测试环境 codeblock minGW

测试代码

using namespace std;
class A
{
   public:
       int a;
       A(int a){
        this->a=a;
        cout<<"构造函数"<<this<<endl;
        }
       A(){a=1;}
       A(const A & b){
           this->a=b.a;
           cout<<"调用了拷贝构造函数"<<this<<endl;
        }
};
int main()
{
    A a2=ma();
    //cout<<&a2<<endl;
    A a3=ma();
    //cout<<&a3<<endl;
    system("pause");
   return 0;
}

测试结果

结论

地址递减,说明是栈中地址
构造的对象存储在主函数main的栈中
由此可知,只有new的对象才在堆中,其余的类型,不管是基础还是对象,都是在栈中

原文地址:https://www.cnblogs.com/lxzbky/p/13955273.html