我有以下代码:
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/