A
Andrew Brampton
Hi,
This may sound a odd question, but I wanted to know how you return a list of
data from a function. These are some of the ways I know how, and I was
wondering which method you normally use. This is more of a best practices
question rather than a technical one.
1) Return a list instance ie
std::list myFunction() {
std::list list();
return list;
}
This however does a lot of copying and isn't very efficient, but seems
conceptually the easiest.
2) Return a list pointer (or reference) ie
std::list * my Function() {
std::list *list = malloc(sizeof(std::list));
return list;
}
This only needs to copy a pointer, however this list must now be deleted. If
we passed the address of say a member variable (or global variable) then we
don't need to delete, but make sure it doesn't change before the caller is
finished using it.
3) Return a iterator ie,
std::list::iterator myFunction() {
std::list list;
return list.begin();
}
This has little copying again, but we also need to know the list.end() maybe
from another method.
4) Pass the list in
void myFunction(std::list &list) {
// Fill the list with stuff
}
Again little copying, sounds a good idea.
Each has pros and cons but this may sound like a silly question, but which
method is most "advisable" from a API point of view? For example if I was
writing a API for other developers to use, which would be the best?
Thanks very much
Andrew
P.S Would the answer to this question be any different if it was a set,
vector, or map?
This may sound a odd question, but I wanted to know how you return a list of
data from a function. These are some of the ways I know how, and I was
wondering which method you normally use. This is more of a best practices
question rather than a technical one.
1) Return a list instance ie
std::list myFunction() {
std::list list();
return list;
}
This however does a lot of copying and isn't very efficient, but seems
conceptually the easiest.
2) Return a list pointer (or reference) ie
std::list * my Function() {
std::list *list = malloc(sizeof(std::list));
return list;
}
This only needs to copy a pointer, however this list must now be deleted. If
we passed the address of say a member variable (or global variable) then we
don't need to delete, but make sure it doesn't change before the caller is
finished using it.
3) Return a iterator ie,
std::list::iterator myFunction() {
std::list list;
return list.begin();
}
This has little copying again, but we also need to know the list.end() maybe
from another method.
4) Pass the list in
void myFunction(std::list &list) {
// Fill the list with stuff
}
Again little copying, sounds a good idea.
Each has pros and cons but this may sound like a silly question, but which
method is most "advisable" from a API point of view? For example if I was
writing a API for other developers to use, which would be the best?
Thanks very much
Andrew
P.S Would the answer to this question be any different if it was a set,
vector, or map?