为什么不鼓励在堆上创建 std::string/std::map ? [英] Why is std::string/std::map not encouraged to be created on the heap?

查看:54
本文介绍了为什么不鼓励在堆上创建 std::string/std::map ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到在多个问题上,C++ 专家询问 std::string/std::map/etc.不应使用 'new' 关键字创建(C++ 新手,如果不明显的话).

I have noticed on multiple questions, C++ experts asking that std::string/std::map/etc. should not be created with the 'new' keyword (newbie to C++, if it wasn't obvious).

所以,如果我的理解是正确的,这不会在堆上而是在堆栈上创建它.这意味着一旦函数超出范围,对象就会消失,但我认为事实并非如此,我的理解是错误的.

So, if my understanding is correct this would not create it on the heap but on the stack. This would mean that the moment the function goes out of scope, the object would disappear, but I believe that is not the case and my understanding is wrong.

这是因为底层模板在堆上实例化它并使用 auto_ptr 管理它,所以它不会导致内存泄漏?这是否适用于所有 stl 类?

Is this because the underlying template instantiates it on the heap and manages it using an auto_ptr, so that it doesn't cause a memory leak? Does this apply for all stl classes?

此外,一个后续问题是创建插入到地图中的对象的方法应该是什么?是否应该在堆上分配它们(如果它们在函数范围之外有价值)?

Also, a follow up question is what should be the approach to create objects that are inserted in maps? Should they be allocated on the heap (if they are valuable out of the scope of the function)?

我确实了解堆和堆栈之间的区别以及使用它们的原因(我可能不清楚这一点).

I do understand the difference between heap and stack and the reasons for using each (I probably was not clear about this).

我要求这样做的原因是它似乎不自然,只是为我想保留的对象实例化堆栈上的一个对象.但是,我想这就是语法的样子.

The reason I ask for this is it seems unnatural, to just instantiate an object on the stack for an object I'd like to keep around. But, I guess this is just how the syntax looks like.

这意味着,当我写作时,我觉得我在堆栈上有一些东西,

This means, I feel like I'm having something on the stack when I write,

std::map<int,int> mymap;

代替,

std::map<int,int> *mymap = new std::map<int,int>;

我也想知道这对内存的影响.既然现在内存是由这个实现自己清理的,是不是类似于Java中的垃圾收集?使用 stl 对象时是否有隐含的性能影响?

I'm also wondering about the impact of this on the memory. Since now the memory is cleaned up by this implementation itself, is it analogous to garbage collection in Java? Is there an implied performance impact when using an stl object?

推荐答案

把东西放在堆上的一个常见原因是编译时不知道大小,你需要灵活分配一些未知数的对象.stringmap 的内部实现以及其他容器将根据需要自动从堆中分配,从而减轻您的负担.将对象本身放在堆上变得多余.

One of the common reasons for putting something on the heap is that the size isn't known at compile time, and you need the flexibility of allocating some unknown number of objects. The internal implementations of string and map and the other containers will automatically allocate from the heap as necessary, relieving you of that burden. Putting the object itself on the heap becomes redundant.

将容器放在堆上的唯一原因是当您需要它的生命周期比创建它的块更长时.

The only reason to put a container on the heap is when you need its lifetime to be longer than the block that creates it.

这篇关于为什么不鼓励在堆上创建 std::string/std::map ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆