Is it safe to pass an unconstructed buffer to the constructor of std::ostream?

Deadly 提交于 2019-12-11 23:09:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!