关于如何将std :: ostream对象的地图打交道的问题?
我正在处理以下类属性:
std::map <std::ostream*, std::string> colors;
我想知道是否有一种方法可以用更好的数据结构来替换ostream
的指针?我阅读
地图
仅用于存储信息并访问它以执行简单的操作,而无需修改ostream
对象,而只是简单地比较,替换或添加它们到地图
本身。
提前致谢。
I am dealing with the following class attribute:
std::map <std::ostream*, std::string> colors;
I was wondering if there is a way to replace the pointer to ostream
with a better data-structure? I read here that using a smart-pointer in this case is not a good idea and may be useless.
The map
would be used only to store information and to access it to do simple stuff, without modifying the ostream
objects, but simply comparing, replacing or adding them to the map
itself.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
原始指针不应用于管理动态分配的对象的寿命。正如您所提到的那样,我认为
std :: Ostream
s在其他地方存储在其他地方,而指针只是指示:它们指向某个地方。他们不参与所有权,也不需要。特别是这意味着您确定对象生命结束后未使用指针。如果所有这些都适用,那么就不需要智能指针,因为智能指针是管理对象寿命的指针。原始指针是不参与终身管理的指针。在有明智的指针之前,有原始的指针和不拥有的原始指针,而且一切都更加混乱。如今,原始的拥有指针可以并且应该完全避免,而原始的指针和智能指针实际上并不是相同用例的替代方法。
当然,这取决于您要使用地图的目的。考虑到生命周期的所有权和管理,原始指针只是指示指针没有参与所有权的正确选择,并且显然没有其他需要用其他东西代替它们。
Raw pointers should not be used to manage lifetime of dynamically allocated objects. As you mention nothing that goes against that, I assume the
std::ostream
s are stored elsewhere while your pointers are just pointers: They point somewhere. They do not participate in ownership, and they do not need to. In particular that means you are sure that the pointers are not used after the objects lifetime ended.If all that applies then there is no need for smart pointers, because smart pointers are pointers that manage lifetime of objects. Raw pointers are pointers that do not participate in lifetime management. Before there were smart pointers there were owning raw pointers and non-owning raw pointers, and everything was much more messy. Nowadays, raw owning pointers can and should be avoided completely, and raw pointers and smart pointers aren't really alternatives to be considered for the same use cases.
This of course depends on what you want to use the map for. Considering ownership and managment of lifetime a raw pointer is just the right choice to signal that the pointer does not participate in ownership and there is no apparent need to replace them with something else.