C++11 auto declaration with and without pointer declarator

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

    It doesn't matter as far as the interpretation of the C++ code goes; you can write whatever you want. However, there is a question of style and readability: Generally, you should not hide pointer, reference and CV qualifiers, and perhaps even smart pointers, in type aliases, since it makes it harder for the reader to understand that that's what's going on. Type aliases should package the semantically relevant type content, whereas qualifiers and modifiers should remain visible. So prefer the following:

     using Foo = long_namespace::Foobrigation;
     using MyFn = const X * (int, int);
    
     std::unique_ptr MakeThatThing(MyFn & fn, int x)   // or "MyFn * fn"
     { 
         const auto * p = fn(x, -x);
         return p ? p->Create() : nullptr;
     }
    

    And don't say:

    using PFoo = std::unique_ptr;   // just spell it out
    using MyFn = int(&)(int, int);       // unnecessary; & is easy to spell
    auto p = fn(x, -x);                  // Don't know that p is a pointer
    

    Note also that reference qualifiers (unlike pointers) genuinely change the type of the variable that's being declared, so they're not optional:

    X & f();
    auto a = f();    // copy!
    auto & b = f();  // b is the same as the return value of f()
    

    Finally, adding explicit const pointer qualifications can help const-correctness. Consider the next example, in which a container contains pointers-to-mutable, but we only require const access. Just auto * would deduce a pointer to mutable, which we can avoid by saying const explicitly:

    std::vector v = /* ... */;
    for (const auto * p : v)
    {
        observe(p->foo());   // no need for a mutable *p
    }
    

提交回复
热议问题