#include <unordered_set>
class C {
public:
std::unordered_set<int> us;
};
int main() {
C* c;
c->us.insert(2); // Segmentation Fault
}
我做错了什么?
最佳答案
你得到一个段错误,因为指针还没有被分配:
C* c = new C; // <<== Add this
c->us.insert(2);
delete c; // <<== Free the memory
与声明为对象而不是指针的对象不同(例如 C c;
),指针需要初始化:您应该为它们分配现有对象的地址,或者为新对象分配内存使用运算符 new
。取消引用未初始化的指针被认为是未定义的行为,通常会导致段错误。
关于c++ - 带有指向持有 unordered_set 的对象的指针的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17730545/