Fast way of returning a string
Hello Everyone,
I'm writing a set of classes and I want to be able to print out information about their objects. I want something similar to the to_s function in Ruby or ToString() in Java. Kind of like this,
class MyClass
{
public:
char* ToString();
};
Then be able to do
printf("%s%s", foo.ToString(), bar.ToString());
The problem is that this will cause a memory leak. ToString() will be forced to allocate the char array and then the pointer will be lost once it's passed into printf. Also doing a lot of string allocation while the game is running doesn't seem like a good idea. I have thought about using a pool of strings but this seems like it would introduce lots of complexity.
Does anyone know of a good solution for this kind of thing?
Return a std::string instead of a raw pointer. If it's a performance problem (I.e. you've profiled it and discovered this is a significant problem), then you could keep the string as a member variable and return a const reference to it instead of returning it by value.
Quote:Original post by frc
Does anyone know of a good solution for this kind of thing?
std::string to the rescue! It looks like your code is a mix of C and C++ (the two languages are not the same!). Pick one and stay with it. Since you're using classes, you've selected C++. As a general rule, this means you should be using std::cout for printing to standard out (instead of nasty printf) and you should be using std::string when dealing with strings.
[edit]
Blasted! The number of times a moderator has ninja'd me is ridiculous. I mean really.
ninja'd++;
If you only use ToString for printing you might also consider overloading the ostream operator instead, see this page.
The moderators are out to get you [wink]
Quote:Original post by MikeTacular
Blasted! The number of times a moderator has ninja'd me is ridiculous. I mean really.
ninja'd++;
The moderators are out to get you [wink]
Hello,
instead of "printf("%s%s", foo.ToString(), bar.ToString());" which sounds very procedural to me, why not have "foo.Print(), bar.Print();" ?
It probably shouldn't be hard to create some kind of inheritance graph of printable objects.
Isn't it their own responsibility to print themselves?
instead of "printf("%s%s", foo.ToString(), bar.ToString());" which sounds very procedural to me, why not have "foo.Print(), bar.Print();" ?
It probably shouldn't be hard to create some kind of inheritance graph of printable objects.
Isn't it their own responsibility to print themselves?
Or better: Program actual C++, not C, i.e. use std::[cout|cerr], and look into the following: How can I provide printing for my class Fred?.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement