【发布时间】:2020-09-25 11:20:48
【问题描述】:
在下面的c++中调用reset()里面的list、vector、map既没有错误也没有警告。
但是,当我尝试在 set 中执行此操作时出现错误。
错误消息是[没有匹配的成员函数调用'reset']
为什么会这样???有人可以与社区分享您的知识吗?
std::shared_ptr<int> sp;
sp.reset(new int(11));
sp.reset();
std::map<int, std::shared_ptr<int>> my_map;
for (auto it = my_map.begin(); it != my_map.end(); ++it) {
it->second.reset();
(*it).second.reset();
}
std::list<std::shared_ptr<int>> my_list;
for (auto& x : my_list) {
x.reset();
}
std::vector<std::shared_ptr<int>> my_vec;
for (auto it = my_vec.begin(); it != my_vec.end(); ++it) {
it->reset();
(*it).reset();
}
std::set<std::shared_ptr<int>> my_set;
for (auto& x : my_set) {
x.reset(); // ERROR!!!
}
for (auto it = my_set.begin(); it != my_set.end(); ++it) {
it->reset(); // ERROR!!!
(*it).reset(); // ERROR!!!
}
- 操作系统:Ubuntu18.04
- 编译器:g++ 7.5.0-3ubuntu1~18.04
【问题讨论】:
-
请不要在您显示的minimal reproducible example 中添加行号,这让我们很难复制它来尝试自己。如果您想指出一些特定的行,请在这些行上添加 cmets 并在主要问题正文中提及它们。
-
std::set<>的键是const,这是有充分理由的。如果它们被更改,这可能会违反它们的顺序,但明确定义的顺序对于std::set(用于查找)至关重要。因此,我确信for (auto& x : my_set)中的auto&会导致const引用,而std::shared_ptr中显然没有reset() const。 -
修改键可能会破坏作为集合的属性;每个值只出现一次。 (它也可能会破坏排序,但我认为这是一个较小的问题。)
-
@Someprogrammerdude 我编辑删除了行数,谢谢
标签: c++ c++11 smart-pointers stdset