C++ 函数内局部变量的生命周期

270 阅读1分钟

函数内局部变量的生命周期,是在赋值给返回值后结束的。但是函数返回值变量的生命周期是会被上层接收的。

#include "stdio.h"
#include <string>
using namespace std;

static int _count = 0;

class MyString{
	char *_str;
	int _id;
public: 
	MyString(const char *p){
		_id = _count++;
		int len = strlen(p)+1;
		_str = (char *)malloc(len);
		memcpy(_str,p,len);
		printf("--------ctor MyString id=%d\n",_id);
	}

	MyString(const MyString& b){
		_id = _count++;
		int len = strlen(b._str)+1;
		_str = (char *)malloc(len);
		memcpy(_str,b._str,len);
		printf("--------clone ctor MyString id=%d\n",_id);
	}

	char* c_str(){
		return _str;
	}
	int getId(){
		return _id;
	}
	~MyString(){
		printf("destruct MyString id=%d\n",_id);
		free(_str);
	}
};

MyString test1(){
	MyString str("test object");
	return str;
}

MyString test2(){
	MyString str("test char*");
	return str.c_str();
}

int main()
{
	MyString str = test1();
	printf("str = %s; id = %d\n",str.c_str(),str.getId());
	return 0;
}

如test1所示,当返回值和实际接收的类型相同时,test1中的str被main给接收了,不会创建新的String变量。

--------ctor MyString id=0
str = test object; id = 0
destruct MyString id=0

若接收类型不相同时,则触发构造函数,构造一个新的String.

--------ctor MyString id=0
--------ctor MyString id=1
destruct MyString id=0
str = test char*; id = 1
destruct MyString id=1