Search code examples
c++c++11referenceauto

Why do 'auto' and explicit reference variable declarations behave differently?


I have something like this:

class Bar;

class Foo()
{
 public:
   Foo() : bar(new Bar());
   Bar& GetBar() { return *bar.get(); }
 private:
   std::unique_ptr<Bar> bar;
};

void main()
{
   Foo foo;
   auto bar1 = foo.GetBar();
   auto bar2 = foo.GetBar(); //address of bar2 != address of bar1. why?

   Bar& bar3 = foo.GetBar();
   Bar& bar4 = foo.GetBar(); //address of bar3 == address of bar4.
}

It seems the 'auto' variables are copies as I don't get Bars back with the same memory address. If I explicitly define the variables as Bar references (Bar&) then everything works as I would expect.

I'm compiling in VS2012. What's going on here?


Solution

  • auto works like template argument deduction. bar1 and bar2 have types Bar, so they are independent copies; bar3 and bar4 have type Bar & and are references to the same *foo.bar.