C++引用类型作为函数返回值类型的简单了解

#include<iostream>

using namespace std;

/**
 * 返回局部变量的引用回导致非法访问栈区的内存
 * @return a 局部变量a的引用
 */
int& returnReferenceOfLocalVariable(){
    //非静态局部变量存储在栈区,由编译器负责其内存的分配和释放, 在函数调用完成后释放, 内存被回收
    int a = 10;
    //return local variable's alias
    return a;
}

/**
 * 可以返回静态局部变量的引用, 因为其存储在全局区, 其内存的分配和释放由操作系统负责, 在程序执行前即存在, 在程序执行完后才释放
 * @return a 静态局部变量的引用
 */
int& returnReferenceOfStaicLocalVariable(){
    //返回值类型为引用类型的函数调用可以作为左值接收赋值, 即给被取别名的变量赋值
    static int a = 20;
    //return static variable's alias
    return a;
}

/**
 * 引用类型作为函数的返回值
 * 1,不要返回局部变量的引用
 * 2,返回值类型为引用类型的函数调用可以作为左值(即可以被赋值)
 */
int main() {
    int &ret = returnReferenceOfLocalVariable();
    //call function "returnReferenceOfLocalVariable" and let ret receive it return value
    cout << "ret = " << ret << endl;
    cout << "ret = " << ret << endl;
    //output:
    //ret = 10
    //ret = 10
    //because of the complier's reasons, the output is the same twice,
    //in fact, the first should be output 10, the second should be output a random integer

    int &ret2 = returnReferenceOfStaicLocalVariable();
    cout << "ret2 = " << ret2 << endl;
    cout << "ret2 = " << ret2 << endl;

    //function's call as left value
    returnReferenceOfStaicLocalVariable() = 1000;
    cout << "ret2 = " << ret2 << endl;
    cout << "ret2 = " << ret2 << endl;

    system("pause");

    return 0;
}

 

posted @ 2020-08-08 11:14  DNoSay  阅读(761)  评论(0编辑  收藏  举报