C++临时对象的析构

C++中要特别注意临时对象的析构时间点,不然很容易犯错,甚至不知道错在哪里。下面是用到str()和c_str()犯的一个错误

举个例子

#include <iostream>
#include<sstream>
using namespace std;

void print(const char* c)
{
	string str;

	printf("%s", c);
}
int  main()
{

	stringstream ss;
	ss << "hello world";
    print(ss.str().c_str());

}

上面这个程序可以打印得到hello world,将上面这个程序改一下,

#include <iostream>
#include<sstream>
using namespace std;


int  main()
{
	stringstream ss;
	ss << "hello world";
	const char *c = ss.str().c_str();
	printf("%s", c);
}

这时就出现问题了,因为ss.str()返回的是一个string临时变量,c_str()对其去地址,但是当遇到语句结束时即这一句的";"时,这个临时变量就被析构掉了,因此指针c指向的地址的值也就没有了,因此得不到hello world。当然我们可以将临时对象付给一个变量保存,然后再利用c_str()方法,像下面这样

#include <iostream>
#include<sstream>
using namespace std;


int  main()
{
	stringstream ss;
	ss << "hello world";
	string str= ss.str();
	const char *c = str.c_str();
	printf("%s", c);
}



猜你喜欢

转载自blog.csdn.net/alatebloomer/article/details/81044329