[英]string concatenation using streams returns junk
I probably should start stating that I'm pretty new with C++, and, since I come from a higher level language, I may be missing some technical issues that I can't identify. 我可能应该开始说说我对C ++相当陌生,并且由于我来自高级语言,所以我可能会缺少一些我无法确定的技术问题。
I have the following method: 我有以下方法:
const char * Point::toString() const {
std::ostringstream stream;
stream << "[" << x << ", " << y << "]"; //[3, 5] for example
return stream.str().c_str();
}
I'm then calling it like this: 然后我这样称呼它:
Point p1 (3, 5);
std::cout << p1.toString() << std::endl;
However, this prints some junk. 但是,这会打印一些垃圾。
What am I doing wrong? 我究竟做错了什么? Also, is my
toString()
method really efficient? 另外,我的
toString()
方法真的有效吗? Am I leaking memory by allocating a new char *
and never freeing it? 我是否通过分配新的
char *
而不释放它来泄漏内存?
The char pointer returned by string::c_str()
is only valid for the lifetime of the string (and only when it is not modified). string::c_str()
返回的char指针仅在字符串的生存string::c_str()
有效(并且只有在未修改的情况下)。
But stream.str()
returns a temporary string object, which you need to store somewhere. 但是
stream.str()
返回一个临时字符串对象,您需要将其存储在某个地方。 Otherwise it will be destroyed after that exact statement you call that function. 否则,它将在您调用该函数的确切语句后销毁 。
But even if you write 但是即使你写
string result = stream.str();
return result.c_str();
then you destroy the string object inside of the function, invalidating the char pointer returned by c_str()
and resulting in undefined behavior as soon as it is used (dereferenced). 然后销毁函数内部的字符串对象, 使
c_str()
返回的char指针无效 ,并在使用(取消引用)后立即导致未定义的行为。
In the end, the best is to just return a string: 最后,最好是只返回一个字符串:
return stream.str();
您可以只返回strdup (stream.str().c_str())
,但是您应该自己管理此内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.