在 std::set 容器中使用常量字符指针:内存消耗

发布于 2024-10-18 00:34:40 字数 249 浏览 3 评论 0原文

我目前正在使用一个内存很少(4MB)的设备,并且我的程序中有一个需要 std::set 的组件。我想将此集从使用 std::string 迁移到使用 const char 指针,但我想知道在 std::set 中使用时如何将内存分配给常量字符指针。

当指针从集合中删除(通过使用 .clear() 或超出范围)时,为 std::set 的每个条目分配的内存是否会被释放,或者字符串文字是否会保留在内存中直到集合结束程序的执行?

非常感谢您的帮助。 :)

I'm currently working on a device with very little memory (4MB) and I have a component of my program that requires an std::set. I would like to migrate this set from using std::string to using const char pointers but I was wondering how memory is allocated to constant character pointers when used in a std::set.

Will the memory allocated for each entry to the std::set be freed when the pointer is removed from the set (by using .clear() or going out of scope), or will the string literal remain in memory until the end of the program's execution?

Thank you very much for your help. :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

不如归去 2024-10-25 00:34:40

简而言之,不会发生什么特别的事情。

删除包含指向某些内存的指针的结构只会释放指针本身使用的内存;它不会导致所指向的内存发生任何事情。

当然,除非您显式调用 free/delete 。对于字符串文字来说这不是一个好主意!

In short, nothing special will happen.

Deleting a structure that contains a pointer to some memory will only free the memory used by the pointer itself; it will not cause anything to happen to the pointed-to memory.

Unless, of course, you explicitly call free/delete on it. Which is not a good idea in the case of string literals!

倥絔 2024-10-25 00:34:40

STL 容器在清理它们时总是为其包含的元素调用默认析构函数。对于持有原始“char *”指针的集合,这不会执行任何操作,并且内存将被泄漏。你有责任自己清理 ip 这类内存。

因此,在 STL 容器中存储原始指针通常被认为是不好的做法。

如果您确实必须使用其中包含原始 C 字符串的 STL 集,那很好,但请注意您必须自己回收内存。您还需要为该集合提供一个自定义比较器,以便按值而不是按指针比较存储的字符串(“char * 上的默认排序仅比较指针,而不是字符串”)。

The STL containers always calk the default destructors for elements they contain when they are cleaned up. For a set holding raw ‘char *‘ pointers, this will do nothing and the memory will be leaked. You are responsible for cleaning ip this sort of memory yourself.

For this reason, it's generally considered bad practice to store raw pointers in STL containers.

If you really must use an STL set with raw C strings in it, that's fine, but do be aware that you'll have to reclaim the memory yourself. You will also need to provide a custom comparator to the set so that e stored strings are compared by value rather than by pointer (the default ordering on ‘char *‘s just compares the pointers, not the strings).

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