What I understand is that this shouldn\'t be done, but I believe I\'ve seen examples that do something like this (note code is not necessarily syntactically correct but the
It's perfectly legal, but with large structs there are two factors that need to be taken into consideration: speed and stack size.
It is not safe to return a structure. I love to do it myself, but if someone will add a copy constructor to the returned structure later, the copy constructor will be called. This might be unexpected and can break the code. This bug is very difficult to find.
I had more elaborate answer, but moderator did not like it. So, at your expence, my tip is short.
It is perfectly safe to return a struct as you have done.
Based on this statement however: Because my understanding is that once the scope of the function is over, whatever stack was used to allocate the structure can be overwritten, I would imagine only a scenario where any of the members of the structure was dynamically allocated (malloc'ed or new'ed), in which case, without RVO, the dynamically allocated members will be destroyed and the returned copy will have a member pointing to garbage.
The lifetime of the mystruct
object in your function does indeed end when you leave the function. However, you are passing the object by value in the return statement. This means that the object is copied out of the function into the calling function. The original object is gone, but the copy lives on.
The safety depends on how the struct itself was implemented. I just stumbled on this question while implementing something similar, and here is the potential problem.
The compiler, when returning the value does a few operations (among possibly others):
mystruct(const mystruct&)
(this
is a temporary variable outside the function func
allocated by the compiler itself)~mystruct
on the variable that was allocated inside func
mystruct::operator=
if the returned value is assigned to something else with =
~mystruct
on the temporary variable used by the compilerNow, if mystruct
is as simple as that described here all is fine, but if it has pointer (like char*
) or more complicated memory management, then it all depends on how mystruct::operator=
, mystruct(const mystruct&)
, and ~mystruct
are implemented.
Therefore, I suggest cautions when returning complex data structures as value.
A structure type can be the type for the value returned by a function. It is safe because the compiler is going to create a copy of struct and return the copy not the local struct in the function.
typedef struct{
int a,b;
}mystruct;
mystruct func(int c, int d){
mystruct retval;
cout << "func:" <<&retval<< endl;
retval.a = c;
retval.b = d;
return retval;
}
int main()
{
cout << "main:" <<&(func(1,2))<< endl;
system("pause");
}