问题
This is a convenient way to define a subclass of ostream that sets a buffer (MyStreamBuf is some subclass of std::streambuf):
class MyOStream : public std::ostream {
public:
MyOStream(): std::ostream(&buffer) {}
// ...
private:
MyStreamBuffer buffer;
};
Here std::ostream's constructor is called before the constructor of buffer, so the streambuf* being passed in is pointing to an unconstructed object that has virtual methods. The same issue applies in ~MyStream(), as buffer is destructed before std::ostream is, so the destructor of std::ostream will be looking at a destructed buffer object.
I have heard that this technique is safe because the standard does not allow std::ostream to call methods on the buffer in its constructor and destructor. Is that true?
Note that the question is not whether this will actually work with current implementations of the standard library, the question is whether it is guaranteed to work by the standard. The question is also not how to rewrite the code above to get around the issue - for example by using multiple inheritance to get the buffer to be constructed as a super class before the std::ostream super class.
来源:https://stackoverflow.com/questions/12931999/is-it-safe-to-pass-an-unconstructed-buffer-to-the-constructor-of-stdostream