Reputation: 163
Should I use example 1 or example 2 for map pointer from find_if to object Which one is the best?
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);
}
Upvotes: 0
Views: 233
Reputation: 68701
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. If you cannot be sure that this is the case, then copy the shared_ptr
by value, as in example
.
Upvotes: 1