猿问

C ++ 11“自动”语义

当我使用C ++ 11时auto,关于类型归纳将解析为值还是引用的规则是什么?


例如,有时很明显:


auto i = v.begin(); // Copy, begin() returns an iterator by value

这些不太清楚:


const std::shared_ptr<Foo>& get_foo();

auto p = get_foo(); // Copy or reference?


static std::shared_ptr<Foo> s_foo;

auto sp = s_foo; // Copy or reference?


std::vector<std::shared_ptr<Foo>> c;

for (auto foo: c) { // Copy for every loop iteration?


素胚勾勒不出你
浏览 507回答 3
3回答

慕森王

规则很简单:这就是您声明的方式。int i = 5;auto a1 = i;&nbsp; &nbsp; // valueauto & a2 = i;&nbsp; // reference下一个例子证明了这一点:#include <typeinfo>#include <iostream>&nbsp; &nbsp;&nbsp;template< typename T >struct A{&nbsp; &nbsp; static void foo(){ std::cout<< "value" << std::endl; }};template< typename T >struct A< T&>{&nbsp; &nbsp; static void foo(){ std::cout<< "reference" << std::endl; }};float& bar(){&nbsp; &nbsp; static float t=5.5;&nbsp; &nbsp; return t;}int main(){&nbsp; &nbsp; int i = 5;&nbsp; &nbsp; int &r = i;&nbsp; &nbsp; auto a1 = i;&nbsp; &nbsp; auto a2 = r;&nbsp; &nbsp; auto a3 = bar();&nbsp; &nbsp; A<decltype(i)>::foo();&nbsp; &nbsp; &nbsp; &nbsp;// value&nbsp; &nbsp; A<decltype(r)>::foo();&nbsp; &nbsp; &nbsp; &nbsp;// reference&nbsp; &nbsp; A<decltype(a1)>::foo();&nbsp; &nbsp; &nbsp; // value&nbsp; &nbsp; A<decltype(a2)>::foo();&nbsp; &nbsp; &nbsp; // value&nbsp; &nbsp; A<decltype(bar())>::foo();&nbsp; &nbsp;// reference&nbsp; &nbsp; A<decltype(a3)>::foo();&nbsp; &nbsp; &nbsp; // value}输出:valuereferencevaluevaluereferencevalue

慕码人8056858

无论您从右侧(等于“ =”)获得什么,都永远不会成为参考。更具体地说,表达式的结果永远不会是引用。因此,请注意示例中结果之间的差异。#include <typeinfo>#include <iostream>template< typename T >struct A{&nbsp; &nbsp; static void foo(){ std::cout<< "value" << std::endl; }};template< typename T >struct A< T&>{&nbsp; &nbsp; static void foo(){ std::cout<< "reference" << std::endl; }};float& bar(){&nbsp; &nbsp; static float t=5.5;&nbsp; &nbsp; return t;}int main(){&nbsp; &nbsp;auto a3 = bar();&nbsp; &nbsp;A<decltype(bar())>::foo(); // reference&nbsp; &nbsp;A<decltype(a3)>::foo();&nbsp; &nbsp; // value}
随时随地看视频慕课网APP
我要回答