Search code examples
c++function-object

Does `name_compare()` calls the default construction or the `operator()` of `class name_compare` in `sort(vs.begin(), vs.end(), name_compare());`?


Does name_compare() calls the default construction or the operator() of class name_compare in sort(vs.begin(), vs.end(), name_compare());?

I think it's the first one.Am i right?

I would be thankful for any hint on this question.

 struct Record {
        string name;
        // ...
    };
    struct name_compare {   // compare Records using "name" as the key
        bool operator()(const Record& a, const Record& b) const
            { return a.name<b.name; }
    };
    void f(vector<Record>& vs)
    {
        sort(vs.begin(), vs.end(), name_compare());
        // ...
    }   

Solution

  • In this call

    sort(vs.begin(), vs.end(), name_compare());
    

    there is created a temporary object of the type name_compare as a function argument using the default constructor. Within the function std::sort there is called the operator function of the object.

    Here is a demonstrative program

    #include <iostream>
    #include <string>
    
    struct Record
    {
        std::string name;
    };
    
    struct name_compare 
    {
        name_compare()
        {
            std::cout << "name_compare() is called\n";
        }
    
        bool operator()( const Record &a, const Record &b ) const
        {
            std::cout << "operator () is called\n";
            return a.name<b.name; 
        }
    };
    
    int main() 
    {
        Record a = { "A" };
        Record b = { "B" };
    
        if ( name_compare()( a, b ) ) std::cout << a.name << " is less than " 
                                                << b.name << '\n';
    
    
        return 0;
    }
    

    Its output is

    name_compare() is called
    operator () is called
    A is less than B
    

    In this expression

    name_compare()( a, b )
    

    there called constructor creating a temporary object

    name_compare()( a, b )
    ^^^^^^^^^^^^^^
    

    and then there is called the operator function of the created object

    name_compare()( a, b )
                  ^^^^^^^^
    

    To make it more clear you can rewrite the expression the following way

    name_compare().operator ()( a, b )