问题描述
说我有以下代码(这只是一个示例,显然不实际):
std::list <Object> objects;
Object cur_object;
for(int i = 0; i < 11; i++){
switch(i){
case 0:
cur_object.foo = true;
break;
case 5:
case 10:
objects.push_back(cur_object);
Object cur_object; //Line in question
break;
default:
cur_object.bar = i;
break;
}
}
最有效和最有效的方法是“重置”下一次通过cur_object
。例如,我不相信cur_object = *new Object
是正确的。最好让该类具有reset方法吗?
解决方案:
在为我的用例查看了建议的方法的性能之后,它们非常接近,彼此之间的距离都在0.5%之内,但是objects.emplace_back()
方法是最有效的。
解决方法
您可以通过简单地将多余的对象保留在列表的末尾来完全规避这一点:
std::list<Object> objects;
objects.emplace_back(); // temporary object is at the end of objects
for(int i = 0; i < 11; i++){
switch(i){
case 0:
objects.back().foo = true;
break;
case 5:
case 10:
objects.emplace_back(); // current becomes stored,add new temporary
break;
default:
objects.back().bar = i;
break;
}
}
objects.pop_back(); // get rid of temporary
pop_back
足够便宜,以至于整个收藏集一次完成就不成问题,而且您不必担心将临时文件移入列表并进行重新设置。>
您可以使用new放置在旧对象的存储中构造一个新对象。但是,要在行为的定义端,需要将curObject
转换为指针:
char storage[sizeof(Object)]; //this is where we will store the object
Object* curObject = new(storage) Object(); //construct an Object within the storage
...
curObject->~Object(); //explicitly call destructor to tear down the old object
curObject = new(storage) Object(); //the storage can be reused now
此方法的优点是,即使Object
的赋值运算符被删除,它也可以工作。