如何解决为什么在我的程序中两次调用了运算符?
#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",hcount);
return 0;
}
运行代码,我得到:
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
我不明白为什么在insert()期间两次调用operator()。 应该只叫一次吗?
感谢分享您的想法。
解决方法
大概是您在使用libc ++。带有libc ++的Clang表现出这种行为。带有libstdc ++的Clang没有。
initializer list insert调用range insert,后者调用__hashtable::__insert_multi,后者调用__construct_node,其中hashes,之后__insert_multi调用__node_insert_multi,后者也{{ 3}}。
我认为没有什么标准可以阻止这种情况,因此可能只是“ QoI”。
,看来结果取决于每个编译器。 vc ++和g ++的标准输出如下:
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
clang ++的标准输出(与您的相同)如下:
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
上测试代码
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。