【问题标题】:use of "&" with auto [duplicate]将“&”与自动一起使用[重复]
【发布时间】:2017-06-21 18:14:27
【问题描述】:

什么时候需要使用“&”,什么时候不需要?
例如在下面,两个 for 循环都会产生相同的结果。

std::vector< Product* > itemByColor = pF.by_color( vecProds, Color::Red );

for( auto i : itemByColor )
{
     std::cout << " product name <<" << i->name<< std::endl;
}

for( auto& i : itemByColor )
{
     std::cout << " product name <<" << i->name<< std::endl;
}

【问题讨论】:

  • 只要读取值,copy和reference应该没有太大区别
  • @sp2danny:对于较小的对象,例如ints,获取引用实际上会降低性能。

标签: c++11 c++14


【解决方案1】:

与您决定输入std::string 还是(conststd::string&amp; 大致相同。也就是说,无论您是要复制对象还是引用它。

std::vector<int> my_vector{ 1, 2, 3, 4, 5 };

int copy = my_vector[ 0 ];
int& reference = my_vector[ 0 ];

++copy;
std::cerr << my_vector[ 0 ] << '\n'; // Outputs '1', since the copy was incremented, not the original object itself

++reference;
std::cerr << my_vector[ 0 ] << '\n'; // Outputs '2', since a reference to the original object was incremented

// For each 'n' in 'my_vector', taken as a copy
for( auto n : my_vector )
{
    // The copy ('n') is modified, but the original remains unaffected
    n = 123;
}

// For each 'n' in 'my_vector', taken as a reference
for( auto& n : my_vector )
{
    // The original is incremented by 42, since 'n' is a reference to it
    n += 42;
}

// At this point, 'my_vector' contains '{ 44, 44, 45, 46, 47 }'

【讨论】:

  • 直奔主题!
猜你喜欢
  • 2020-05-05
  • 2017-08-16
  • 2011-01-13
  • 2018-11-18
  • 2015-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多