16

I'm working with some code today, and I saw:

extern std::locale g_classicLocale;
class StringStream : public virtual std::ostringstream
{
 public:
        StringStream() { imbue(g_classicLocale); }
        virtual ~StringStream() {};
};

Then I came in face of imbue. What is the purpose of the imbue function in C++? What does it do? Are there any potential problems in using imbue (non-thread safe, memory allocation)?

Mat
  • 202,337
  • 40
  • 393
  • 406
cybertextron
  • 10,547
  • 28
  • 104
  • 208
  • 5
    http://en.cppreference.com/w/cpp/io/basic_ios/imbue – juanchopanza Aug 06 '12 at 15:55
  • 1
    There is a problem deriving from ostringstream – Daniel Aug 06 '12 at 15:56
  • @Dani Only if you decide to dynamically allocate it and then use it polymorphically, which would be rather unusual for a stream – Praetorian Aug 06 '12 at 15:57
  • @Dani: Philippe is right, there is no real issue in deriving from `std::ostringstream`, as it has been designed for inheritance and polymorphism. Note that `ios_base` has a virtual destructor, the types in the hierarchy are all designed to be polymorphical. – David Rodríguez - dribeas Aug 06 '12 at 16:20
  • 3
    @Prætorian: That is not really true: the type **is** designed to be used polymorphically. Even dynamically allocating and releasing through *any* of the bases will work (`ios_base` has a virtual destructor) – David Rodríguez - dribeas Aug 06 '12 at 16:21

2 Answers2

22

imbue is inherited by std::ostringstream from std::ios_base and it sets the locale of the stream to the specified locale.

This affects the way the stream prints (and reads) certain things; for instance, setting a French locale will cause the decimal point . to be replaced by ,.

Praetorian
  • 106,671
  • 19
  • 240
  • 328
8

C++ streams perform their conversions to and from (numeric) types according to a locale, which is an object that summarizes all the localization information needed (decimal separator, date format, ...).

The default for streams is to use the current global locale, but you can set to a stream a custom locale using the imbue function, which is what your code does here - I suppose it's setting the default C locale to produce current locale-independent text (this is useful e.g. for serialization purposes).

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299