C++中几种变量声明的比较

只有打好基础才能写出高质量的程序,只有搞清楚了变量到底是建立在栈上的,还是建立在堆上才能有效避免内存泄漏。

看这个例子:

#include <stdio.h>
class test
{
public:
    test(){printf("constructor/n");}
    test(int a){printf("aconstructor/n");}
    ~test(){printf("destructor/n");}
};

int main()
{
    test a;         // 1
    test *b;       // 2
    test c();      // 3
    test d(1);    // 4
    test *e = new test();  // 5
    return 0; 
}

输出
1:
constructor
destructor
栈上局部变量

2:
无输出
BSS段

3:
无输出
编译器警告: 仅仅是变量定义?

4:
aconstructor
destructor
仍然是局部变量,栈上自动处理

5:
constructor
堆上分配,未调用析构,内存泄漏!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值