Prevent unnecessary copies of C++ functor objects

后端 未结 5 1136
野的像风
野的像风 2020-12-09 10:39

I have a class which accumulates information about a set of objects, and can act as either a functor or an output iterator. This allows me to do things like:



        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 11:05

    If you have a recent compiler (At least Visual Studio 2008 SP1 or GCC 4.4 I think) you can use std::ref/std::cref

    #include 
    #include 
    #include  // for std::cref
    #include 
    #include 
    
    template 
    class SuperHeavyFunctor 
    {
        std::vector v500mo;
        //ban copy
        SuperHeavyFunctor(const SuperHeavyFunctor&);
        SuperHeavyFunctor& operator=(const SuperHeavyFunctor&);
    public:
        SuperHeavyFunctor():v500mo(500*1024*1024){}
        void operator()(const T& t) const { std::cout << t << std::endl; }
    };
    
    int main()
    {
        std::vector v; v.push_back("Hello"); v.push_back("world");
        std::for_each(v.begin(), v.end(), std::cref(SuperHeavyFunctor()));
        return 0;
    }
    

    Edit : Actually, the MSVC10's implementation of reference_wrapper don't seem to known how to deduce the return type of function object operator(). I had to derive SuperHeavyFunctor from std::unary_function to make it work.

提交回复
热议问题