简体   繁体   English

关于如何将 std::ostream 对象映射到类中的问题?

[英]Question about how to deal with a map of std::ostream objects into a class?

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?我想知道是否有办法用更好的数据结构替换指向ostream的指针? 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.map将仅用于存储信息并访问它以执行简单的操作,而无需修改ostream对象,而只需将它们比较、替换或添加到map本身。

Thanks in advance.提前致谢。

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.正如您没有提到任何与此相反的内容,我假设std::ostream存储在其他地方,而您的指针只是指针:它们指向某个地方。 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.如今,可以并且应该完全避免原始拥有指针,并且原始指针和智能指针并不是在相同用例中考虑的真正替代方案。

I was wondering if there is a way to replace the pointer to ostream with a better data-structure?我想知道是否有办法用更好的数据结构替换指向 ostream 的指针?

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.考虑到生命周期的所有权和管理,原始指针只是表明指针不参与所有权并且没有明显需要用其他东西替换它们的正确选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM