Is it safe to return a struct in C or C++?

后端 未结 12 1884
北海茫月
北海茫月 2020-12-04 07:55

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

12条回答
  •  抹茶落季
    2020-12-04 08:48

    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.

提交回复
热议问题