11

我有这样的事情:

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.
}

似乎“自动”变量是副本,因为我没有返回具有相同内存地址的 Bars。如果我将变量明确定义为 Bar 引用 (Bar&),那么一切都会按我的预期工作。

我应该提到我正在编译vs2012。这里发生了什么?

谢谢。

4

3 回答 3

22
于 2013-01-25T17:01:57.253 回答
13

auto像模板参数推导一样工作。bar1并且bar2有类型Bar,所以它们是独立的副本;bar3并且bar4有类型Bar &并且是对相同的引用*foo.bar

于 2013-01-25T16:49:36.533 回答
1

Code:

X& getter() {
    static X value;
    return value;
}

print("X:");
X x0 = getter();
auto x0a = getter();
x0.printAddress();
x0a.printAddress();

print("X&:");
X& x1 = getter();
auto& x1a = getter();
x1.printAddress();
x1a.printAddress();

print("const X&:");
const X& x2 = getter();
const auto& x2a = getter();
x2.printAddress();
x2a.printAddress();

print("X&&:");
print("Rvalue can't be bound to lvalue");
X&& x3 = getter();
auto&& x3a = getter();
x3.printAddress();
x3a.printAddress();

Result:

X:
0037F807
0037F7FB
X&:
00D595BA
00D595BA
const X&:
00D595BA
00D595BA
X&&:
Rvalue can't be bound to lvalue
00D595BA

Conclusion:

auto means: "replace me with type, unless I am auto&& then find the most suitable form".

于 2013-01-29T21:49:17.810 回答