Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'auto' and explicit variable declaration behaving differently

Tags:

c++

c++11

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 should mention I'm compiling in vs2012. What's going on here?

Thanks.

like image 951
Aeluned Avatar asked Jan 25 '13 16:01

Aeluned


People also ask

What is the difference between implicit and explicit variable declaration?

Explicit variable declaration means that the type of the variable is declared before or when the variable is set. Implicit variable declaration means the type of the variable is assumed by the operators, but any data can be put in it.

What is implicit variable?

Implicit variables are variables that you do not define. These variables are automatically provided by the framework. Some implicit variables are not associated with any other variables, while other implicit variables are valid only when they are associated with a variable that you declare.

Is it possible to declare and define a variable at the same time?

Once something is defined, that also counts as declaring it; so you can often both declare and define a function, class or variable at the same time.

Can you declare and initialize multiple variables with a single expression?

You can declare several variables in one declaration statement, specifying the variable name for each one, and following each array name with parentheses. Multiple variables are separated by commas.


2 Answers

auto bar1 = … always declares a copy. auto &&bar1 selects the closest possible reference type, which is what you want.

auto && is the perfect forwarding idiom.

You can also use other compound types with auto, such as auto const & or auto * if you want to be specific.

like image 150
Potatoswatter Avatar answered Oct 06 '22 21:10

Potatoswatter


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.

like image 26
Kerrek SB Avatar answered Oct 06 '22 20:10

Kerrek SB