[英]std::find_if map to object
Should I use example 1 or example 2 for map pointer from find_if to object Which one is the best? 对于find_if到object的地图指针,我应该使用示例1还是示例2,哪个最好?
struct test {
INT id
}
std::vector<std::shared_ptr<test>> vec;
int ID = 75;
auto obj = std::find_if(vec.begin(), vec.end(), [&ID](std::shared_ptr<test>& r){
return r->id == ID;
});
if ( obj != vec.end() ) {
// example 1
std::shared_ptr<test> example1 = (*obj);
// example 2 by reference
std::shared_ptr<test>& example2 = (*obj);
}
If you will not modify vec
between the call to find_if
and the usage of the shared_ptr
, then take a reference to the element as in example2
to avoid unnecessary adjustments to the reference count. 如果您不会在对find_if
的调用和shared_ptr
的用法之间修改vec
,那么请像example2
那样对元素进行引用,以避免对引用计数进行不必要的调整。 If you cannot be sure that this is the case, then copy the shared_ptr
by value, as in example
. 如果不能确定是否确实如此, shared_ptr
值复制shared_ptr
, example
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.