Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BOOST_FOREACH implicit use of reference?

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;
}
like image 900
Jamie Cook Avatar asked May 14 '26 01:05

Jamie Cook


1 Answers

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()) {}
}
like image 166
visitor Avatar answered May 15 '26 14:05

visitor