On Friday, May 11, 2012 6:30:52 AM UTC-5, Juha Nieminen wrote:
> Assume that I have something along the lines of:
>
> //----------------------------------------------------
> struct Something
> {
> std::vector<SomethingElse> aBigVector;
> std::set<FooBar> aBigSet;
> };
> //----------------------------------------------------
>
> and then I inadvertently do something like this:
>
> //----------------------------------------------------
> std::vector<Something> container;
> populate(container);
>
> for(auto element : container)
> // code that does not modify 'element'
> //----------------------------------------------------
>
> What I *should* have done is, of course, this:
>
> //----------------------------------------------------
> for(const auto& element : container)
> ...
> //----------------------------------------------------
>
> Or even just:
>
> //----------------------------------------------------
> for(auto& element : container)
> ...
> //----------------------------------------------------
>
> If, however, I mistakenly do it without a reference, will the compiler
> be able to optimize the copying of the large elements if it sees that
> they are not modified in the loop body?
>
> If the compiler is unable to optimize the copying away, I'm thinking
> that the range-based loop is way too easy to use in an inefficient manner
> by mistake. This is not a very good thing.
I've thought about that also, but probably if an author
isn't aware of it, someone will catch it in a code review.
I remember a thread a few months ago about studying code
from a project. If such an author studied this code --
http://webEbenezer.net/misc/direct.tar.bz2
they might notice the use of & in this context and
investigate it further.
http://webEbenezer.net