简体   繁体   中英

What '&' stands for in “std::vector<byte>& stream;”

I know that

void foo(vector<int>& v) { ... }

is passing vector by reference, but

std::vector<byte>& stream;

what is that stream variable definition? Why '&' is there?

It's a reference to a std::vector<byte> . Because it is a reference, it allows you to change the original vector , as shown in this example:

#include <iostream>
#include <vector>

class Incrementer {
public:
    Incrementer(std::vector<int>& v) : vec(v) {}
    void increment() {
        for (auto& i : vec)
            ++i;
    }
private:
    std::vector<int>& vec;
};

int main() {
    std::vector<int> numbers { 1, 2, 3, 4 };
    Incrementer inc(numbers);
    for (auto i : numbers)
        std::cout << i << ' ';
    std::cout << '\n';

    inc.increment();

    for (auto i : numbers)
        std::cout << i << ' ';
    std::cout << '\n';
}

inc will hold a reference to numbers , so calling inc.increment() changes numbers :

1 2 3 4 
2 3 4 5 

As others said, both of these two are the references. However, the second one is not valid as there is no referenced variable! It should be written in some way like this:

#include <vector>
#include <iostream>

int main()
{
    std::vector<int> stream1(5);
    stream1[0] = 10;
    std::vector<int>& stream2 = stream1; // stream2 and stream1 are two names for the same variable
    stream1[0] += 55;
    cout << "stream1: " << stream1[0] << endl;
    cout << "stream2: " << stream2[0];
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM