c++ - 愚蠢的STL问题

标签 c++ memory-management stl

我有以下代码:

customObject* object;
std::list<customObject> objects;
for(int i = 0; i < 10: ++i) {
   object = new customObject;
   object.getvalue(i);
   objects.push_back(*object);
}

成功退出后内存会被释放吗?

对不起,伙计们。犯了一些错误))已修复

最佳答案

由于您已将 std::list 声明为:

std::list<customObject> objects; //not storing the pointers!

那么您就不需要使用new 创建customObject。你应该这样做:

std::list<customObject> objects;
for(int i = 0; i < 10; ++i) {
   customObject object;
   object.getvalue(i);
   objects.push_back(object); //store the object, not pointer!
}

在 C++0x 中,这可以用 lambda 表达式非常简洁地完成,如:

std::list<customObject> objects(10);
int i=0;
std::for_each(objects.begin(),objects.end(),[&](customObject &obj){ 
     obj.getValue(i++);
 });

关于c++ - 愚蠢的STL问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5991712/

相关文章:

c++ - 从arduino中串行接收的数据解析整数

c++ - 为什么我的 HelloWorld 函数没有在这个范围内声明?

STL - STL 的实际文档

c++ - C++ 中的 STL 容器实际上是如何实现的..

c++ - 为什么STL比较函数不是成员?

c++ - 从另一个元组类型的嵌套类型派生元组类型

c++ - 无法使用 OOP C++ 打印堆栈项

objective-c - 帮助我了解 Objective-C 和 Cocoa 中的内存管理

c++ - 测量(自定义)分配器的执行时间?

c - 中止陷阱 :6 for fopen