Re: Do compilers optimise away copies of vectors that are returned by functions?
On 21/04/2011 21:45, John Reid wrote:
Suppose I have the following struct:
struct A {
std::vector< int> v;
std::vector< int> fn() { return v; }
}
and the following code that uses it:
A a;
for( size_t i = 0; 100 != i; ++i ) {
a.v.push_back(0);
}
a.fn()[20]; //How efficient is this line?
Will modern compilers realise that I am not altering a.v in the given
use case and not copy the vector before accessing the 20th element?
Are they bound to make the copy by the standard?
As v is not local to fn() NRVO should not be invoked; operator[] will be
returning a non-const reference after all. As you are not doing
anything with the result of operator[] the optimizer will likely
optimize that out completely. RVO may still be invoked on the actual
object being returned if making a copy:
std::vector<int> v = a.fn(); // RVO should ensure no temporary vector is
created.
/Leigh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]