Computer Science Canada

[C++] String Composing Tip

Author:  wtd [ Tue Mar 16, 2004 8:50 pm ]
Post subject:  [C++] String Composing Tip

For composing long strings the temptation is to use the std::string class and its + operator. However, this results in a temporary std::string object being created each time the operator is used. Sometimes compilers can optimize this away, but it shouldn't be counted on.

Instead use the std::stringstream class.

code:
#include <sstream>
#include <iostream>

int main()
{
   std::stringstream ss;

   ss << "hello";
   ss << " ";
   ss << "world" << std::endl;

   std::cout << ss.str();

   return 0;
}


The same way you should use operator overloading to handle output, you can overload it to handle interactions with std::stringstream.

code:
#include <sstream>

class my_class
{
   private:
      int a, b;
   public:
      my_class(int, int);
      friend std::stringstream& operator<<(std:stringstream&, const my_class&);
};

int main()
{
   std::stringstream ss;
   my_class c(4, 3);

   ss << c << std::endl;

   return 0;
}

my_class:my_class(int init_a = 0, int init_b = 0)
: a(init_a), b(init_b)
{ }

std::stringstream& operator<<(std:stringstream& s, const my_class& m)
{
   return s << m.a << " " << m.b;
}


: