I've just begun using c++ and I was wondering if there was some guideline around when to do the following:
Let's say I want to return a struct or object. Which of these approaches would be better under what circumstances?
void PopulateStruct(MyStruct* struct) {
struct->a = x;
struct->b = y;
}
void Caller() {
MyStruct s;
PopulateStruct(&s);
}
OR:
MyStruct PopulateStruct() {
MyStruct s;
s.a = x;
s.b = y;
return s;
}
void Caller() {
MyStruct s = PopulateStruct();
}
My basic understanding is that if the struct / object is pretty small then the latter option is probably fine (better?) since the copy will be fast and compilers might also use RVO to avoid an actual copy.
And perhaps if the object is really large then you want the former to avoid that copy?