我已经设置了这个例子:
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
在这里创建一个拷贝?
最佳答案
set
中的对象不同于 create()
的本地对象。 set
中的那些是使用复制构造函数和移动构造函数构造的,而不是构造函数 UsefulClass(int)
,因此您看不到它们的构造。当函数 create()
返回时,局部对象被销毁,然后 set
中的对象在 main
结束后的全局清理中被销毁。
关于c++ - 为什么对象在插入集合后会被删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17065620/