#include <unordered_set>
class C {
public:
std::unordered_set<int> us;
};
int main() {
C* c;
c->us.insert(2); // Segmentation Fault
}
我在做什么错?指向持有unordered_set的对象的指针的分段错误
#include <unordered_set>
class C {
public:
std::unordered_set<int> us;
};
int main() {
C* c;
c->us.insert(2); // Segmentation Fault
}
我在做什么错?指向持有unordered_set的对象的指针的分段错误
你得到一个分割的错,因为指针尚未分配:
C* c = new C; // <<== Add this
c->us.insert(2);
delete c; // <<== Free the memory
不像声明为对象的对象,而不是指针(如C c;
)指针需要初始化:您应该为它们分配一个地址使用运算符new
为新对象分配内存。解引用未初始化的指针被认为是未定义的行为,通常导致分段错误。
甚至更好,根本不要制造“新”C,因为你不需要。只要做'C c; c.us.insert(2);' – IdeaHat
问题中的代码不是我正在编写的实际代码。这是我的问题最简单的形式,仍然产生了分段错误。在我的实际代码中,“c”(实际上并不是“c”)需要是一个指针。 – anthropomorphic
menory没有为'c'对象 –
哇配置。这真是愚蠢。暂时还没有使用C++,你能告诉吗? = P – anthropomorphic