拥有流的streambuf持续到流的破坏之外吗? [英] Having a stream's streambuf persist beyond stream's destruction?
问题描述
在源流的销毁销毁后,是否有可能使流的 streambuf
持久存在?
Is it possible to have a stream's streambuf
persist after the destruction of its originating stream's destruction?
streambuf* f() {
ifstream my_stream;
// ...
return my_stream.rdbuf();
}
void g() {
streambuf *s = f();
// ...
ifstream my_new_stream;
my_new_stream.rdbuf( s );
}
即,我希望指向 f()
返回的 streambuf
对象的指针即使在 my_stream
超出范围后也保持有效.稍后,我想将其他流的 streambuf
设置为保存的 streambuf
.
I.e., I want the pointer to the streambuf
object returned by f()
to remain valid even after my_stream
goes out of scope. At some later time, I want to set some other stream's streambuf
to the saved streambuf
.
这可能吗?如果可以,怎么办?
Is this possible? If so, how?
推荐答案
这是不可能的. std :: ifstream
构造,拥有并销毁其缓冲区.通过 rdbuf
导出"的唯一原因是允许重定向 std :: cin
等.在GNU实现中,缓冲区是一个简单的成员(不是指针).
It's not possible. std::ifstream
constructs, owns and destroys its buffer. The only reason it's "exported" through rdbuf
is to allow redirection of std::cin
etc. In the GNU implementation, the buffer is a simple member (not a pointer).
std :: ifstream
不会导出带有参数的 rdbuf()
成员.它的父类之一可以,但是应该重新定义 std :: basic_ifstream
中带有签名的 rdbuf
的影子
std::ifstream
does not export the rdbuf()
member with an argument. One of its parent classes does, but this should be shadowed by the redefinition of rdbuf
in std::basic_ifstream
with signature
std::filebuf *rdbuf() const;
std :: filebuf
也是不可复制的.
( rdbuf(std :: streambuf *)
成员可以通过强制转换为 std :: ios
来检索.使用此方法会导致熟悉的鼻恶魔.)
(The rdbuf(std::streambuf *)
member can be retrieved by casting to std::ios
. Using this will cause the familiar nasal demons.)
这篇关于拥有流的streambuf持续到流的破坏之外吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!