gpt4 book ai didi

c++ - 将 std::stream 对象从一个管理器传递到另一个管理器

转载 作者:搜寻专家 更新时间:2023-10-31 01:46:14 26 4
gpt4 key购买 nike

我正在为我的游戏实现 ResourceManager,我遇到了一个关于 Streams 的小问题。

在我的资源管理器中,有一个用于搜索文件的定位器对象。当定位器找到文件时,它返回一个 ResourceStream 对象(virtual ResourceStream * FileLocator::locateFile(const String &name);)。然后,Loader 对象解析文件并创建 Resource 对象(例如 virtual Resource * ResourceLoader::parseStream(ResourceStream * stream);)。

问题是,我不知道如何实现 ResourceStream,因为我真的不知道 std::streams 是如何使用的。作为一种好的做法,流是如何在对象之间传递的?考虑到流将在范围末尾被删除,它应该通过指针传递还是移动语义?在上面的问题中,我应该如何使流移动?我应该让 ResourceStream 继承自 std::fstream 并通过 std::move 传递它吗?或者我应该使用 ResourceStream 作为 std::streambuf 的包装器吗?

最佳答案

考虑实现 stream buffer (可以作为参数传递)。当您需要缓冲区上的 I/O 时,在其上创建一个 std::istream 或 std::ostream。

这种方法将允许您使用 std::[i/o]stream 访问正确格式化的 I/O 而无需您的任何努力(即您只需要定义添加或从流中获取字节意味着,而不是格式化。

代码应该是这样的:

class ResourceStream: public std::streambuf {
... // you implement this
};

virtual Resource parseStream(std::streambuf * streambuf)
{
std::istream in(streambuf);
Resource r;
in >> r; // assumes an std::istream& operator>>(std::istream&in, Resource& r)
// is defined
if(in >> r)
return r;
else
throw std::runtime_error{"bad stream for parsing resource"};
}

编辑:

仔细一看,这似乎是 x-y 问题。正确的解决方案是为您的 Resource 类定义 i/o 运算符:

你需要写什么:

class Resource {
// ...
};

std::istream& operator >> (std::istream& in, Resource& r) {
return in after reading from it
}
std::ostream& operator << (std::ostream& out, const Resource& r) {
return in after writing into it
}

在您的模型中,ResourceStream 对象将是一个在找到的文件上打开的 std::ifstream,您的 ResourceManager 将如下所示:

// boost::path can be replaced by std::string containing the file path
virtual boost::path FileLocator::locateFile(const String &name);

// locate file and get resource:
auto path = locator.locateFile("serializedresource.data");
std::ifstream input(path);
Resource r;
if(input >> r)
// r was read correctly
else
// stream does not contain a serialized r / throw an exception

关于c++ - 将 std::stream 对象从一个管理器传递到另一个管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20954061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com