dimanche 25 novembre 2018

C++ returning a reference

How is a function returning a reference different from initializing a reference with a regular return value?

int f1() {
    static int i = 10;
    return i;
}

int& f2() {
    static int i = 10;
    return i;
}

int main() {
    const int &v1 = f1();
    printf("%d\n", v1);

    int v2 = f2();
    printf("%d\n", v2);    
}

What's the difference between

int f1();
const int &v1 = f1();

and

int& f2();
int v2 = f2();

Aucun commentaire:

Enregistrer un commentaire