Say I have an array, and I want to retrieve a reference to an element of this array.
struct A {
int n;
}
A& search_algo(A* AList, int len, int target) {
for (int i = 0; i < len; i++) {
if (AList[i].n == target) { return AList[i]; }
}
return what? //problem comes here, target not in array, what should I return
}
I would like to know what is the most conventional way to deal with it, or what return value makes the most sense. Like how can I best convey a message of "your thing isn't here, go away". Something similar to a nullptr
would be great.
My current solution is to initialize a object A
on the stack and return it. Although I can compile just fine, but returning a reference to local variable is unsafe.
I am thinking initializing the object on heap using new
but that would be messy and I will have to deal with memory release. I don't like it.
Aucun commentaire:
Enregistrer un commentaire