【发布时间】:2020-08-24 11:50:31
【问题描述】:
我有一个结构:
struct Foo
{
std::unordered_map<std::string, std::string> info;
int count;
int bar;
}
我正在尝试按如下方式在堆上初始化此结构:
Foo* createFoo(int count, int bar)
{
Foo* foo = (Foo*)malloc(sizeof(Foo));
foo->info = std::unordered_map<std::string, std::string>(); // <- exception thrown here
foo->count = count;
foo->bar = bar;
return foo;
}
我在构造 unordered_map 时遇到以下异常:
Exception thrown: read access violation. _Pnext was 0xCDCDCDD1.
我知道 MVS 用 0xCD 填充堆分配的内存,这就是为什么 _Pnext 指针有这个值,但我不明白为什么 unordered_map 构造函数没有将这些字段归零。
我意识到现代 C++ 执行此操作的方式是使用 new/constructors,但我正在尝试使用(基本上)POD 对象以非 OOP 程序方式编写此代码。
我是不是初始化地图不正确?
【问题讨论】:
-
A
unordered_map绝不是 POD 类型。既然知道应该怎么做,为什么还要这样做? -
使用
new不是“现代”方式;自从 C++ 被称为“C with classes”以来,它一直是的方式。它也与 OOP 完全无关。 -
@chips C++ 是多范式语言,OOP 是它支持的范式之一。这与初始化
std::unordered_map无关,您在初始化Foo时遇到了问题。Foo的初始化将初始化其所有成员。 -
我可以推荐一个好的C++ Book。将节省大量时间。
-
我是不是初始化地图不正确?你根本没有初始化地图。
标签: c++ class constructor initialization malloc