开发者

C++11 auto: what if it gets a constant reference?

开发者 https://www.devze.com 2023-03-29 20:38 出处:网络
Please take a look at the following simple code: class Foo { public: Foo(){} ~Foo(){} Foo(const Foo&){}

Please take a look at the following simple code:

class Foo
{
public:
  Foo(){}
  ~Foo(){}

  Foo(const Foo&){}
 开发者_如何学Python Foo& operator=(const Foo&) { return *this; }
};

static Foo g_temp;
const Foo& GetFoo() { return g_temp; }

I tried to use auto like this:

auto my_foo = GetFoo();

I expected that my_foo will be a constant reference to Foo, which is the return type of the function. However, the type of auto is Foo, not the reference. Furthermore, my_foo is created by copying g_temp. This behavior isn't that obvious to me.

In order to get the reference to Foo, I needed to write like this:

const auto& my_foo2 = GetFoo();
      auto& my_foo3 = GetFoo();

Question: Why does auto deduce the return type of GetFoo as an object, not a reference?


Read this article: Appearing and Disappearing consts in C++


Type deduction for auto variables in C++0x is essentially the same as for template parameters. (As far as I know, the only difference between the two is that the type of auto variables may be deduced from initializer lists, while the types of template parameters may not be.) Each of the following declarations therefore declare variables of type int (never const int):

auto a1 = i;
auto a2 = ci;
auto a3 = *pci;
auto a4 = pcs->i;

During type deduction for template parameters and auto variables, only top-level consts are removed. Given a function template taking a pointer or reference parameter, the constness of whatever is pointed or referred to is retained:

template<typename T>
void f(T& p);

int i;
const int ci = 0;
const int *pci = &i;

f(i);               // as before, calls f<int>, i.e., T is int
f(ci);              // now calls f<const int>, i.e., T is const int
f(*pci);            // also calls f<const int>, i.e., T is const int

This behavior is old news, applying as it does to both C++98 and C++03. The corresponding behavior for auto variables is, of course, new to C++0x:

auto& a1 = i;       // a1 is of type int&
auto& a2 = ci;      // a2 is of type const int&
auto& a3 = *pci;    // a3 is also of type const int&
auto& a4 = pcs->i;  // a4 is of type const int&, too

Since you can retain the cv-qualifier if the type is a reference or pointer, you can do:

auto& my_foo2 = GetFoo();

Instead of having to specify it as const (same goes for volatile).

Edit: As for why auto deduces the return type of GetFoo() as a value instead of a reference (which was your main question, sorry), consider this:

const Foo my_foo = GetFoo();

The above will create a copy, since my_foo is a value. If auto were to return an lvalue reference, the above wouldn't be possible.


You can take simple answer as granted by MSVC Technical documentation:

Using auto drops references, const qualifiers, and volatile qualifiers.

You don't need a function to achieve similar results. Consider:

int var;
const int & cref = var;
auto avar = cref;

The type of avar will be int not const int & nor int &.

To go a bit deeper into this we can go to cppreference.com and refer to template argument deduction analogy.

For example, given const auto& i = expr;, the type of i is exactly the type of the argument u in an imaginary template template<class U> void f(const U& u).

We tend to intuitively use templates and until it works we never really bother about template argument deduction rules. These rules are in fact quite complex. But we can make the "imaginary template for auto" non-imaginary and test what would have happened if we provided auto i = expr; to the template. In our case the template may look like this:

template<class U> 
void f(U u)
{
    cout << type_name<decltype(u)>() << "\n";
}

Let's feed it with variables with types of our interest:

    int i = 0;
    int & ir = i;
    const int & cir = i;
    f(i);
    f(ir);
    f(cir);

And the what's at the output?

int
int
int

The same thing would have happened with auto as predicted by MSVC docs :)

Here's the code if you wanted to play.


Here's also example from MS website if it disappeared one day

// cl.exe /analyze /EHsc /W4
#include <iostream>

using namespace std;

int main( )
{
    int count = 10;
    int& countRef = count;
    auto myAuto = countRef;

    countRef = 11;
    cout << count << " ";

    myAuto = 12;
    cout << count << endl;
}

In the previous example, myAuto is an int, not an int reference, so the output is 11 11, not 11 12 as would be the case if the reference qualifier hadn't been dropped by auto

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号