如下例子
const char* cstr = string("king").c_str();
cout << "cstr : " << (char*)cstr << endl;
输出的是
cstr :
并没有输出king
但是
cout << "cstr : " << string("king").c_str() << endl;
输出
cstr : king
看起来是cstr获取的c_str();被释放了,于是自己写一个class验证了一下
class Student
{
public:
int age;
char name[100];
Student()
:age(0)
{
memset(this->name, 0, 100);
}
Student(int age, const char* name)
:age(age)
{
strcpy_s(this->name, 100, name);
}
~Student()
{
cout << "~Student" << endl;
}
int getAge()
{
return age;
}
};
int a = Student(39, "hello").getAge();
cout << "get age : " << a << endl;
在输出get age : 39的前一行输出了~Student
也就是说cstr输出空字符串,是因为cstr取值string("king").c_str()后只获取了地址,然后string生命周期结束,地址对应的内存区间被释放掉了。
=右边的实例的生命周期只有构造的一瞬间,立马会被释放
=左边的实例的生命周期在代码块内。