C ++:是push_back(new Object())内存泄漏? [英] C++: is push_back(new Object()) a memory leak?

查看:1149
本文介绍了C ++:是push_back(new Object())内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下C ++代码是否为内存泄漏?

Is the following C++ code a memory leak?

list.push_back(new String("hi"));

据我所知,push_back从任何std集合/容器总是做一个副本。所以如果新的字符串被复制,没有什么可以删除新的字符串吗?因为在push_back之后没有引用它...

As I understand it, push_back from any std collection/container always makes a copy. So if the new string is copied, nothing can ever delete the new'd string right? since there is no reference to it after the push_back...

我在这里是正确的还是错误的?

Am I correct or wrong here?

非常感谢。

Jbu

编辑:我认为我错了,因为new会传回指针...我们总是有指针能够删除新的字符串

edit: I think I am wrong, since new will return a pointer...we'll always have the pointer to be able to delete the new String

推荐答案

不,向量存储指针,副本是由指针组成。您可以随时删除该对象。

No, the vector stores pointers and the copy is made of the pointer. You can delete the object any time later.

(如果语句恰巧抛出异常并且您没有正确处理它,您可能会遇到泄漏。这就是为什么你可以考虑使用智能指针。)

(You may get a leak, if the statement happens to throw an exception and you don't catch and handle it properly. That's why you might consider using smart pointers.)

这篇关于C ++:是push_back(new Object())内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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