Does BOOST_FOREACH involve using a link?

I am wondering if there are any advantages to getting a reference to a vector before calling BOOST_FOREACH, or will the method call that returns the link be automatically used? For example, which of the following two cycles will be equivalent to the third cycle?

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;
}
+3
source share
3 answers

Looking through the frenzy of metaprogramming BOOST_FOREACH, I see that the collection is copied if it

  • r value
  • A "lightweight proxy" that you can define for your types by specializing in boost::foreach::is_lightweight_proxy.

Therefore, lvalue is not copied. Instead, its pointer is considered temporary.

Critical bit:

# define BOOST_FOREACH_SHOULD_COPY(COL)             \
     (true ? 0 : boost::foreach_detail_::or_(       \
         BOOST_FOREACH_IS_RVALUE(COL)               \
       , BOOST_FOREACH_IS_LIGHTWEIGHT_PROXY(COL)))

, :

template<typename T> 
inline auto_any<T> contain(T const &t, boost::mpl::true_ *) // rvalue 
{ 
    return t;
}

template<typename T>
inline auto_any<T *> contain(T &t, boost::mpl::false_ *) // lvalue
{
    // Cannot seem to get sunpro to handle addressof() with array types.
    #if BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x570))
    return &t;
    #else
    return boost::addressof(t);
    #endif
}

Boost v1.38 .

+2

, , 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()) {}
}
+4

BOOST_FOREACH - , . ,

my_method()

"" , , . foreach.

, .

0

Source: https://habr.com/ru/post/1735008/


All Articles