c++functionreturnstacknrvo

if I return a class in my function, where does it store?


look at my code:

#include <iostream>
using namespace std;
class MyClass{
public:
    char ch[50] = "abcd1234";
};
MyClass myFunction(){
    MyClass myClass;
    return myClass;
}
int main()
{
    cout<<myFunction().ch;
    return 0;
}

i can't understand where my return value is stored? is it stored in stack? in heap? and does it remain in memory until my program finished?

if it be stored in stack can i be sure that my class values never change?

please explain the mechanism of these return. and if returning structure is different to returning class?


Solution

  • MyClass myClass; is stored on the stack. It's destroyed immediately after myFunction() exits.

    When you return it, a copy is made on the stack. This copy exists until the end of the enclosing expression: cout << myFunction().ch;


    Note that if your compiler is smart enough, the second object shouldn't be created at all. Rather, the first object will live until the end of the enclosing expression. This is called NRVO, named return value optimization.

    Also note that the standard doesn't define "stack". But any common implementation will use a stack in this case.


    if returning structure is different to returning class?

    There are no structures in C++; keyword struct creates classes. The only difference between class and struct is the default member access, so the answer is "no".