I am wondering if there is any benefit to getting a reference to a vector prior to calling BOOST_FOREACH or whether a method call which returns a reference will be automatically used? For example which of the two following loops will be equivalent to the third loop?
vector<float>& my_method();
void main()
{
// LOOP 1 -------------------------------
vector<float>& temp_vector = my_method();
BOOST_FOREACH(float element, temp_vector)
cout << element << endl;
// LOOP 2 -------------------------------
vector<float> temp_vector = my_method();
BOOST_FOREACH(float element, temp_vector)
cout << element << endl;
// Which loop is this one most like? ----
BOOST_FOREACH(float element, my_method())
cout << element << endl;
}
A quick test shows that the function is called once and no copying occurs in connection with BOOST_FOREACH.
#include <vector>
#include <iostream>
#include <boost/foreach.hpp>
struct X
{
X() {}
X(const X& ) { std::cout << "copied\n"; }
};
std::vector<X> vec(2);
//std::vector<X> method()
std::vector<X>& method()
{
std::cout << "returning from method\n";
return vec;
}
int main()
{
BOOST_FOREACH(const X& x, method()) {}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With