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

后端 未结 12 1895
北海茫月
北海茫月 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:35

    I will also agree with sftrabbit , Life indeed ends and stack area gets cleared up but the compiler is smart enough to ensure that all the data should be retrieved in registers or someother way.

    A simple example for confirmation is given below.(taken from Mingw compiler assembly)

    _func:
        push    ebp
        mov ebp, esp
        sub esp, 16
        mov eax, DWORD PTR [ebp+8]
        mov DWORD PTR [ebp-8], eax
        mov eax, DWORD PTR [ebp+12]
        mov DWORD PTR [ebp-4], eax
        mov eax, DWORD PTR [ebp-8]
        mov edx, DWORD PTR [ebp-4]
        leave
        ret
    

    You can see that the value of b has been transmitted through edx. while the default eax contains value for a.

提交回复
热议问题