C++11 auto declaration with and without pointer declarator

后端 未结 6 848
借酒劲吻你
借酒劲吻你 2021-02-03 17:08

What\'s the difference between the types of bar1 and bar2?

int foo = 10;
auto bar1 = &foo;
auto *bar2 = &foo;

6条回答
  •  日久生厌
    2021-02-03 17:32

    In this specific example both bar1 and bar2 are the same. It's a matter of personal preference though I'd say that bar2 is easier to read.

    However, this does not hold true for references as seen in this example:

    #include 
    using namespace std;
    
    int main() {
        int k = 10;
        int& foo = k;
        auto bar = foo; //value of foo is copied and loses reference qualifier!
        bar = 5; //foo / k won't be 5
        cout << "bar : " << bar << " foo : " << foo << " k : " << k << endl;
        auto& ref = foo;
        ref = 5; // foo / k will be 5
        cout << "bar : " << bar << " foo : " << foo << " k : " << k;
        return 0;
    }
    

提交回复
热议问题