码迷,mamicode.com
首页 > 编程语言 > 详细

C++对象生命周期(未完)

时间:2015-08-02 23:29:34      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:c++

1.栈中生成的对象,其作用域为其在的{}中。遇到右括号}后执行析构函数。

2.堆中生成的对象,即new生成的动态对象,需要delete执行析构函数。


<pre name="code" class="cpp">#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
class WithCC {
public:
	int id;
	WithCC(int i):id(i) {printf("执行id为 %d 的WithCC构造函数!\n",id);}
	~WithCC() {printf("执行id为 %d 的WithCC析构函数!\n",id);}
};
WithCC withCC1(1);
static WithCC withCC2(2);
int main() {
	printf("进入main函数!\n");
	WithCC withCC3(3);
	if(true) {
		printf("进入if语句!\n");
		WithCC withCC4(4);
		printf("生成static对象\n");
		static WithCC withCC5(5);
		printf("if语句即将结束!\n");
	}
	WithCC* withCC6 = new WithCC(6);
	//delete withCC_new;
	printf("main函数结束!\n");
	return 0;
}




运行结果为:


技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

C++对象生命周期(未完)

标签:c++

原文地址:http://blog.csdn.net/zqh_1991/article/details/47212383

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!