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?
autoworks like template argument deduction.bar1andbar2have typesBar, so they are independent copies;bar3andbar4have typeBar &and are references to the same*foo.bar.