C++11 auto declaration with and without pointer declarator

后端 未结 6 854
借酒劲吻你
借酒劲吻你 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:41

    There is a big difference when you use const qualifiers:

    int i;
    
    // Const pointer to non-const int
    const auto ip1 = &i; // int *const
    ++ip1; // error
    *ip1 = 1; // OK
    
    // Non-const pointer to const int
    const auto* ip2 = &i; // int const*
    ++ip2; // OK
    *ip2 = 1; // error
    

提交回复
热议问题