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.
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.
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With