比较流
我正在考虑使用流来概括我的 C++ 应用程序中的数据源。但是,我的代码还使用了一个资源管理器,其功能类似于工厂,但其主要目的是确保同一资源不会两次加载到内存中。
myown::ifstream data("image.jpg");
std::ifstream data2("image2.jpeg");
ResourcePtr<Image> img1 = manager.acquire(data);
ResourcePtr<Image> img2 = manager.acquire(data);
cout << img1 == img2; // True
ResourcePtr<Image> img3 = manager.acquire(data2);
cout << img1 == img3; // False
为此,它显然必须进行一些检查。如果资源管理器有数据流作为输入,是否有合理的方法(可读且有效)来实现这一点?
I'm looking into generalizing my data sources in my C++ application by using streams. However, my code also uses a resource manager that functions in a manner similar to a factory, except its primary purpose is to ensure that the same resource doesn't get loaded twice into memory.
myown::ifstream data("image.jpg");
std::ifstream data2("image2.jpeg");
ResourcePtr<Image> img1 = manager.acquire(data);
ResourcePtr<Image> img2 = manager.acquire(data);
cout << img1 == img2; // True
ResourcePtr<Image> img3 = manager.acquire(data2);
cout << img1 == img3; // False
For it to do this, it obviously has to do some checks. Is there a reasonable way (readable and efficient) to implement this, if the resource manager has data streams as input?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法“比较”数据流。流不是容器;而是容器。它们是数据流。
顺便说一句,
cout << a == b
是(cout << a) == b
;我认为你的意思是cout << (a==b)
。You cannot "compare" data streams. Streams are not containers; they are flows of data.
BTW,
cout << a == b
is(cout << a) == b
; I think you meantcout << (a==b)
.数据身份远高于流的抽象级别。考虑一下如果您的流知道该信息,它将如何处理该信息。它无法对其采取行动,它只是一堆数据。就接口而言,流甚至不一定有结束。如果你试图在那个层面上将身份与它联系起来,那么对我来说,你将违反最低限度的惊喜。
不过,这听起来像是您的
ResourcePtr
的合理抽象。当您将数据加载到ResourcePtr
时,您可以对数据进行哈希处理,但文件路径上的键可能也同样好。The level of abstraction where the identity of the data is well above your streams. Think about what your stream would do with that information if it knew it. It could not act upon it, it is just a bunch of data. In terms of the interface, a stream doesn't necessarily even have an end. You would be violating least surprise for me if you tried to tie identity to it at that level.
That sounds like a reasonable abstraction for your
ResourcePtr
, though. You could hash the data when you load it intoResourcePtr
, but a key on the file path is probably just as good.正如托马拉克所说,你无法比较流。您必须将它们包装在某个类中,该类将 ID 与它们相关联,如果它们都与文件系统上的文件相关联,则可能基于绝对路径
Like Tomalak said, you can't compare streams. You'll have to wrap them in some class which associates an ID to them, possibly based on the absolute path if they are all associated to files on the file system