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

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

    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");
    }
    

提交回复
热议问题