Reputation: 5321
I'm a bit new to use of the auto keyword. The project I work on only recently switched to using compilers that all support it. I want to make a code change that I can easily test on only one of the many compilers it will need to be correct on (I'm testing one ICC version. It needs to be correct in multiple versions each of ICC, GCC, and MSVC). So I want to be sure my understanding of this use of auto is correct.
The original code was:
f_y( f_x() );
where f_x() returns a const&
to something and f_y takes a const&
to that same thing. I need to change the code to copy/modify the thing if and only if it really needs to be copied and modified. It may be much too big to copy when it doesn't need to be copied. So I wrote:
auto const& c=f_x();
if ( c.size()==1 && c[0].second<0.0 )
{
auto c_copy = c;
c_copy[0].second = 1.0;
f_y( c_copy );
}
else
f_y( c );
I'm curious whether the const
is really needed on my first use of auto
or whether the compiler deduces that because f_x() returns a const&
. But even if not needed, I'd want it there to make my code understandable as long as none of the compilers are confused by it.
Mainly I'm asking about the second auto. The one compiler I've tested makes that call the copy constructor of the referenced object type (rather than copy just the reference). I'm pretty sure that is the only possible meaning of that code. But I want a bit more confidence that all the versions of ICC, GCC and MSVC that understand auto at all will understand it that way.
BTW, the data type of c[0].first
is known to the compiler, but not known (nor relevant) to the programmer at that point in the source code.
Upvotes: 3
Views: 135
Reputation: 6022
auto
removes references and top-level cv-qualifiers (const
and volatile
).
The type of c
is something const&
and it would be the same even if you wrote auto& c = f_x()
(the same situation as v5
on slide 15 of Scott Meyers' "Type Deduction and Why You Care") so you don't need a const
there.
The type of c_copy
is something
(note: no const
even though the RHS is a const reference; same as v3
on the same slide) , that's why c_copy = c
invokes the copy constructor.
Upvotes: 1