我有这样的事情:
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.
}
Run Code Online (Sandbox Code Playgroud)
似乎'auto'变量是副本,因为我没有使用相同的内存地址返回Bars.如果我明确地将变量定义为Bar引用(Bar&),那么一切都按照我的预期运行.
我应该提到我正在编译vs2012.这里发生了什么?
谢谢.
Pot*_*ter 22
auto bar1 = …
总是宣布一份副本.auto &&bar1
选择最接近的可能引用类型,这是您想要的.
auto &&
是完美的转发习语.
您还可以使用其他复合类型auto
,例如,auto const &
或者auto *
如果您想要特定的.
Ker*_* SB 13
auto
像模板参数演绎一样工作.bar1
并且bar2
有类型Bar
,所以它们是独立的副本; bar3
并且bar4
具有类型Bar &
并且是对它们的引用*foo.bar
.