关于如何将std :: ostream对象的地图打交道的问题?

发布于 2025-02-11 08:55:30 字数 278 浏览 2 评论 0原文

我正在处理以下类属性:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南汐寒笙箫 2025-02-18 08:55:30

原始指针不应用于管理动态分配的对象的寿命。正如您所提到的那样,我认为std :: Ostream s在其他地方存储在其他地方,而指针只是指示:它们指向某个地方。他们不参与所有权,也不需要。特别是这意味着您确定对象生命结束后未使用指针。

如果所有这些都适用,那么就不需要智能指针,因为智能指针是管理对象寿命的指针。原始指针是不参与终身管理的指针。在有明智的指针之前,有原始的指针和不拥有的原始指针,而且一切都更加混乱。如今,原始的拥有指针可以并且应该完全避免,而原始的指针和智能指针实际上并不是相同用例的替代方法。

我想知道是否有一种方法可以用更好的数据结构替换Ostream的指针?

当然,这取决于您要使用地图的目的。考虑到生命周期的所有权和管理,原始指针只是指示指针没有参与所有权的正确选择,并且显然没有其他需要用其他东西代替它们。

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::ostreams 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文