Why operator () is called twice in my program?

Viewed 101
#include <unordered_set>
#include <stdio.h>

int hcount=0;

struct A{
    int i=0;

    A(){}
    A(const A&a) :i(a.i){}

    A(int const & i):i(i) {        
        printf("A ctor i=%d\n", i);
    }

    A&operator=(A &&a){
        this->i= a.i;
        return (*this);
    }
    bool operator==(A const &rhs) const {
        printf("A optor== i=%d\n", this->i);
        return rhs.i == this->i;
    }
};

namespace std{
    template<>
    struct hash<A> { 
        hash() {            
            hcount=0;
        }
        hash(int t) {
            hcount=t;
        }
        std::size_t operator()(A const &a) const {
            ++hcount;
            printf("hash: hcount=%d a.i=%d\n", hcount, a.i);
            return a.i;
        };
    };
}

int  main(int argc, char **argv)
{
    std::initializer_list< A > test={
        {A(1)},
        {A(2)}    
    };

    std::unordered_multiset<A> u(4, std::hash<A>(5) );
    printf("1 ---------test.size is %d hcount is %d\n", test.size(), hcount);
            
    u.insert(test.begin(), test.end() );
    printf("2------------test.size is %d hcount is %d\n", test.size(), hcount);
       
    return 0;
}

Running the code, I got:

A ctor i=1

A ctor i=2

1 ---------test.size is 2 hcount is 5

hash: hcount=6 a.i=1        //operator() is called once for A(1)

hash: hcount=7 a.i=1        //operator() is called twice for A(1)

hash: hcount=8 a.i=2

hash: hcount=9 a.i=2

2------------test.size is 2 hcount is 9

I don't understand why the operator() is called twice during insert(). Should it be called only once?

Thanks for sharing your thoughts.

2 Answers

it seems the result depends on each compiler. stdout of vc++ and g++ are below:

A ctor i=1
A ctor i=2
1 ---------test.size is 2 hcount is 5
hash: hcount=6 a.i=1
hash: hcount=7 a.i=2
2------------test.size is 2 hcount is 7

stdout of clang++ (which is the same with yours) is below:

A ctor i=1
A ctor i=2
1 ---------test.size is 2 hcount is 5
hash: hcount=6 a.i=1
hash: hcount=7 a.i=1
hash: hcount=8 a.i=2
hash: hcount=9 a.i=2
2------------test.size is 2 hcount is 9

you can test your code at https://rextester.com/l/cpp_online_compiler_gcc

Related