Ano*_*ous 1 c++ performance pointers
我想知道比较/对比时性能是否有任何差异
A)在堆上分配对象,将指针放在容器中的那些对象上,在代码中的其他位置操作容器
例如:
std::list<SomeObject*> someList;
// Somewhere else in the code
SomeObject* foo = new SomeObject(param1, param2);
someList.push_back(foo);
// Somewhere else in the code
while (itr != someList.end())
{
(*itr)->DoStuff();
//...
}
Run Code Online (Sandbox Code Playgroud)
B)创建一个对象,将其放入容器中,在代码中的其他位置操作该容器
例如:
std::list<SomeObject> someList;
// Somewhere else in the code
SomeObject newObject(param1, param2);
someList.push_back(newObject);
// Somewhere else in the code
while (itr != someList.end())
{
itr->DoStuff();
...
}
Run Code Online (Sandbox Code Playgroud)
假设指针都已正确解除分配并且一切正常,我的问题是......
如果存在差异,那么会产生更好的性能,差异会有多大?
插入对象而不是指向对象的指针时会出现性能损失.
std::list以及其他std容器创建您存储的参数的副本(std::map复制键和值).
由于您someList是一个std :: list,以下行会复制您的对象:
Foo foo;
someList.push_back(foo); // copy foo object
Run Code Online (Sandbox Code Playgroud)
从列表中检索它时,它将再次被复制.因此,与使用时制作指针副本相比,您正在制作整个对象的副本:
Foo * foo = new Foo();
someList.push_back(foo); // copy of foo*
Run Code Online (Sandbox Code Playgroud)
您可以通过在Foo的构造函数,析构函数,复制构造函数中插入print语句来进行双重检查.
编辑:如评论中所述,pop_front不返回任何内容.你通常会引用front元素front然后你pop_front从列表中删除元素:
Foo * fooB = someList.front(); // copy of foo*
someList.pop_front();
Run Code Online (Sandbox Code Playgroud)
要么
Foo fooB = someList.front(); // front() returns reference to element but if you
someList.pop_front(); // are going to pop it from list you need to keep a
// copy so Foo fooB = someList.front() makes a copy
Run Code Online (Sandbox Code Playgroud)