This is the mail archive of the libstdc++@sourceware.cygnus.com mailing list for the libstdc++ project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: ostringstream problem


 

> I'm having a problem using the ostringstream class.  When I use it
> directly everything works
> out ok, but if I inherit it into another class, I get a segmentation
> fault:

I'm willing to discuss this, but it is my contention that this is not a bug.

I'm curious why you are deriving from ostringstream. The dtor is not 
virtual, and the base class to ostream, basic_ios, must be constructed in 
a way such that basic_ios:init() is called, or else the stream is 
uninitialzed and in an unspecified state--this is what is happening to 
you, and is explicitly endorsed by the standard. See my comments below.

I suggest encapsulating ostringstream, if possible. Or, deriving in a way 
that allows you to specify a basic_ios ctor that is initialized. 

-Benjamin

#include <ios>
#include <sstream>


class Foo : virtual public ostringstream 
{
public:
  //Foo(string init = string()) : ios(new stringbuf(init)), ostream() { }
  Foo(string init = string()) { this->init(new stringbuf(init)); }
  ~Foo() 
  { 
	//deallocate memory? 
  }
};


int main()
{
  string str01;
  stringbuf strbuf(str01);
  ostream osy(&strbuf);
  ostringstream ossy;
  Foo yy;
  
  // 27.4.4.1 basic_ios ctors, p 2
  // basic_ios() constructs an object of class basic_ios leaving its
  // member objects uninitialized. The object must be initialized by
  // calling its init member function. If it is destroyed before it
  // has been initialized the behavior is undefined.

  // as basic_ios::init(sb) is protected, your options are
  // limited. The first thing that comes to mind is using
  // basic_ios::rdbuf(sb*), to actually put some kind of streambuffer
  // and streambuffer state into your ostream: however, it is not
  // guaranteed to initialize your stream, thus still leaving you in
  // undefined territory. I guess you could call init in the ctor, and
  // void the virtual derivation.

  // If your question is, what is the point of creating an object that
  // is forever doomed to wander the land of initialized c++ objects,
  // I would answer: good question. 
  // http://sourceware.cygnus.com/ml/libstdc++/1999-q2/msg00332.html

  // functions that call basic_ios::init(sb)
  // - basic_ios::basic_ios(sb)
  // - basic_istream::basic_istream(sb)
  // - basic_ostream::basic_ostream(sb)

  yy << "Hello world\n";
  return(0);
}





Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]