Scope and return values in C++

前端 未结 6 1210
北恋
北恋 2020-11-30 01:44

I am starting again with c++ and was thinking about the scope of variables. If I have a variable inside a function and then I return that variable will the variable not be \

6条回答
  •  自闭症患者
    2020-11-30 02:37

    It really depends on what kind of variable you are returning. If you return a primitive then it is returned by copy, not by reference so the value is copied to the top of the stack (or, more often placed into a register) where the calling function can get it. If you allocate an object or memory on the heap and return a pointer then it doesn't die because it's on the heap, not the stack. If you allocate something on the stack, however, and return it, that would be a bad thing. For instance, either of these would be very bad:

    int *myBadAddingFunction(int a, int b)
    {
        int result;
    
        result = a + b;
        return &result; // this is very bad and the result is undefined
    }
    
    char *myOtherBadFunction()
    {
        char myString[256];
    
        strcpy(myString, "This is my string!");
        return myString; // also allocated on the stack, also bad
    }
    

提交回复
热议问题