In C++, what does & mean after a function's return type?

后端 未结 11 1435
情歌与酒
情歌与酒 2020-11-29 23:49

In a C++ function like this:

int& getNumber();

what does the & mean? Is it different from:

int getNumb         


        
11条回答
  •  攒了一身酷
    2020-11-30 00:11

    Yes, it's different.

    The & means you return a reference. Otherwise it will return a copy (well, sometimes the compiler optimizes it, but that's not the problem here).

    An example is vector. The operator[] returns an &. This allows us to do:

    my_vector[2] = 42;
    

    That wouldn't work with a copy.

提交回复
热议问题