Sign in to follow this  
frc

Fast way of returning a string

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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++;

Share this post


Link to post
Share on other sites
If you only use ToString for printing you might also consider overloading the ostream operator instead, see this page.

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]

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this