简体   繁体   中英

About the implementations of c++ stl predicate

I wonder how c++ stl predicate is implemented? For example in copy_if() http://www.cplusplus.com/reference/algorithm/copy_if/

According to Effective STL, predicate is passed by value. For the following code for int,

struct my_predicate{
    int var_1;
    float var_2;

    bool operator()(const int& arg){
       // some processing here
    }
}

How is copy_if() implemented regarding to passing value of my_predicate? There are var_1 and var_2 here. For other predicates, there may be different variables in the struct.

If passing by reference or pointer, that is very reasonable to me.

Thanks a lot!

(I hope I'm not misunderstanding your question.)

The reason why it can be passed by value is that the 'my_predicate' struct has an implicit copy constructor automatically generated by the compiler. You can pass it by value because it has a copy constructor.

In practice, It is very likely the compiler will optimise away the copy. In fact it is very likely the compiler will optimise away the entire predicate object and for example in the case of std::copy_if reduce the code to the equivalent of a for loop + if statement.

By convention predicates are passed by value. They are not meant to be heavy weight objects and for small objects even if the entire predicate isn't optimised away, it is faster to pass by value anyway.

Also generally you cannot pass temporary values by non-const reference (let alone pointer) so:

std::copy_if(begin(..),end(..),my_predicate{});

would not compile as your predicate is not a const function. With pass by value you can get away with this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM