Short answer: You are right that you shouldn't delete
, but that's the least of your worries…
You are returning the address of a local variable (i
). That's bad karma.
You could try to fix this as follows (note the two extra &
s):
int * Func(std::vector<int> & integers) {
for (int & i : integers)
if (something)
return &i;
return nullptr;
}
But even then you have a problem, since the vector you're passing in is a temporary ({3, 4, …}
) that gets destroyed before you go past the semicolon. In fact, I don't think it'll even compile, since we're now trying to pass a temporary as an l-value reference.
Since you're using C++11, here's what I think you're trying to accomplish:
std::vector<int> integers = {3, 4, 5, 6, 7};
auto x = std::find_if(begin(integers), end(integers), [](int i) { return something; });
if (x != end(integers)) {
// Use *x…
} else {
// Not found
}