简体   繁体   中英

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? 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.

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.

I was wondering if there is a way to replace the pointer to ostream with a better data-structure?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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