我已经设置了这个例子:
class UsefulClass {
public:
int id;
const bool operator< (const UsefulClass &other) const {
return this->id > other.id;
}
UsefulClass(int _id): id(_id) {
std::cout << "constructing " << id << std::endl;
}
~UsefulClass() {
std::cout << "destructing " << id << std::endl;
}
};
std::set<UsefulClass> set;
void create() {
UsefulClass object_1(1);
UsefulClass object_2(2);
set.insert(object_1);
set.insert(std::move(object_2));
std::cout << "create end" << std::endl;
}
int main() {
create();
std::cout << "main end" << std::endl;
}
我期望对象set
在程序结束时被删除时被破坏一次。但是对象被删除了两次:
constructing 1
constructing 2
create end
destructing 2
destructing 1
main end
destructing 1
destructing 2
为什么要set.insert
在这里创建副本?