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.
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? Am I leaking memory by allocating a new char * and never freeing it?
The char pointer returned by
string::c_str()is only valid for the lifetime of the string (and only when it is not modified).But
stream.str()returns a temporary string object, which you need to store somewhere. Otherwise it will be destroyed after that exact statement you call that function.But even if you write
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).In the end, the best is to just return a string: