分享std :: fstream或std :: stringstream槽std :: iostream [英] Share std::fstream or std::stringstream trough std::iostream

查看:293
本文介绍了分享std :: fstream或std :: stringstream槽std :: iostream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数创建 std :: stringstream std :: fstream 根据条件,

I have a function that creates std::stringstream or std::fstream depending on condition, like:

// Some class, stringStream_ and fileStream_ are members
// obj.Stream() returns std::iostream&
if (condition)
{
    stringStream_.str(std::string());
    obj->Stream().rdbuf(stringStream.rdbuf());
}
else
{
    boost::filesystem::path temp = boost::filesystem::unique_path();
    fileStream_.open(temp.native().c_str(), std::ios_base::trunc | std::ios_base::in | std::ios_base::out);
    obj->Stream().rdbuf(fileStream_.rdbuf());
}

,然后 obj object在另一个线程中处理,所以此时上面的函数可以再次调用,并且 streambuf 在 stringStream 将被重置,并且 fileStream _ 将无法打开新文件,因为它与另一个文件相关联。

and then this obj object is processed in another thread, so at this moment the function above may be called once more and streambuf in stringStream will be reset and fileStream_ will fail to open new file because it is associated with another one.

t会产生 obj.SetStream()的函数,因为流不可复制。

I can't make a function like obj.SetStream() because streams are non-copyable.

问题是:我可以创建 std :: stringstream std :: fstream 并将其传递给对象,使对象成为所有者的流(注意对象存储 std :: iostream ,因为它不知道将传递什么类型的流)。

The question is: how can I create either std::stringstream or std::fstream and pass it to the object so the object becomes an owner of the stream (note object stores std::iostream because it doesn't know what type of stream will be passed).

提前感谢。

推荐答案

您可以传递指针(原始或智能) std :: fstream std :: stringstream 键入指向 std :: iostream 。流的客户端然后只需要做一些 std :: iostream& s = * iostreamPtr; s < yay!; 使用它。

You can pass around a pointer (raw or smart) to dynamically allocated instance of either std::fstream or std::stringstream typed as pointer to std::iostream. The client of the stream then just needs to do something like std::iostream & s = *iostreamPtr; s << "yay!"; to use it.

这篇关于分享std :: fstream或std :: stringstream槽std :: iostream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆