J
Juha Nieminen
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.
//----------------------------------------------------
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.