Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should one never use auto&& for local variables?

While T&& is used with templates as forwarding reference or universal reference (as Scott Meyers calls them), I have seen some blogs use auto&& in code samples. I think auto itself should be enough, however, Herb Sutter in CppCon 2014 says: Never use auto&& for local variables

Why is that?

Seeing all replies , I feel I think I should have asked the contra. The general coding guidelines notwithstanding are there any good use cases of using auto&& inside a function body for code correctness and maintainability .

like image 336
Asterisk Avatar asked Oct 14 '14 07:10

Asterisk


People also ask

Why should we not use driverless cars?

Research has previously suggested that automated vehicles could cause people to drive more than they do, leading to more congestion, energy consumption and pollution.

Is automatic better than manual?

An automatic car makes it easier to focus more on speed and road position – and you can keep both hands on the wheel as you won't have to change gear. You're also unlikely to stall in an automatic – which saves you the embarrassment of making a hash of hill starts or stalling just as the traffic lights change.

Should I put my air purifier on auto?

Auto mode or smart mode is the worst possible setting to leave your air purifier cleaner on. That is, of course, if you care about the air quality in your home. While brands will claim that this mode optimizes the effectiveness of your machine, studies show that these modes are the least efficient at purifying the air.


1 Answers

There are cases when you need a auto&& as a local, consider:

vector<bool> vb { true, false, true };
for( auto&& b : vb )
    b = !b;

Here, a auto& wouldn't do. (if vector<bool> is specialized)

However, the usual reason you use && together with type-deduction
(ie a forwarding reference) is because you don't know or care of the
exact type, you are just going to forward it.

The term 'universal reference' is a bit misleading, you should not use
it universally, hence its changing name to 'forwarding reference'

Note that && not used with type-deduction is a rvalue reference, a different
thing altogether.

like image 116
sp2danny Avatar answered Oct 22 '22 18:10

sp2danny