struct Person {
std::string name;
int id;
};
struct Community {
std::string name;
Person people[2];
};
Community* makeCommunity() {
Community* c = (Community*)operator new(sizeof(Community), std::nothrow);
if(!c) {
std::cout << "Failed to allocate" << std::endl;
std::exit(0);
}
c->name = "Community Name";
c->people[0].name = "Person1";
c->people[0].id = 1;
//Run-time encountered here.
c->people[1].name = "Person2";
c->people[1].id = 2;
return c;
}
我目前正在学习C ++,当程序遇到运行时错误时,我正在测试类似于上面代码的代码,当它尝试在前面提到的函数中执行c->people[1].name = "Person1";
时崩溃了。然而,当我将内存分配为:
Community* c = new Community(std::nothrow);
我对c->people[0].name = "Person1";
完美执行的事实感到困惑,但c->people[1].name = "Person2";
在运行时因为Community
分配内存而失败:
Community* c = (Community*)std::operator new(sizeof(Community), std::nothrow);
有人可以对此有所了解吗?
答案 0 :(得分:1)
电话
Community* c = (Community*)operator new(sizeof(Community), std::nothrow);
不能正确创建Community
类型的对象。它只是为它分配内存。您需要使用展示位置new
运算符来正确初始化对象。
将*c
用作有效的Community
是造成未定义行为的原因。
如果您必须使用operator new
,我建议将该行更改为:
void* ptr = operator new(sizeof(Community), std::nothrow);
Community* c = new (ptr) Community;