What is the difference between references and normal variable handles in C++?

后端 未结 8 822
一生所求
一生所求 2021-01-22 23:33

If C++, if I write:

int i = 0;
int& r = i;

then are i and r exactly equivalent?

8条回答
  •  旧巷少年郎
    2021-01-23 00:07

    You are writing definitions here, with initializations. That means that you're refering to code like this:

    void foo() {
        int i = 0;
        int& r = i;
    }
    

    but not

    class bar {
        int m_i;
        int& m_r;
        bar() : i(0), r(i) { }
    };
    

    The distinction matters. For instance, you can talk of the effects that m_i and m_r have on sizeof(bar) but there's no equivalent sizeof(foo).

    Now, when it comes to using i and r, you can distinguish a few different situations:

    • Reading, i.e. int anotherInt = r;
    • Writing, i.e. r = 5
    • Passing to a function taking an int, i.e. void baz(int); baz(r);
    • Passing to a function taking an int&, i.e. void baz(int&); baz(r);
    • Template argument deduction, i.e. template void baz(T); baz(r);
    • As the argument of sizeof, i.e. sizeof(r)

    In these cases, they're identical. But there is one very important distinction:

    std::string s = std::string("hello");
    std::string const& cr = std::string("world");
    

    The reference extends the lifetime of the temporary it's bound to, but the first line makes its a copy.

提交回复
热议问题