gpt4 book ai didi

c++ - 将数据插入映射变量时出现访问冲突错误

转载 作者:行者123 更新时间:2023-11-30 03:45:03 27 4
gpt4 key购买 nike

我在头文件中声明了一个 map 变量,并尝试从 cpp 文件中的方法向其插入一些值。

在头文件(.h)中,

class Test
{
public:
void AddName(const std::string& name, const std::string& value);
private:
std::map<std::string, std::string> m_names;
};

.cpp文件中,

void Test::AddName(const std::string& name, const std::string& value)
{
m_names.insert(std::pair<std::string, std::string>(name, value));
}

This method throws the error: "0xC0000005: Access violation reading location 0x0000000000000150."

但是如果我在这个 AddName 方法中声明这个映射变量,那么就没有错误。

我正在使用所需参数从另一个类调用此 AddName 方法。

TestPtr test = nullptr;
test->AddName(nodeDetails.Attribute("Name"), nodeDetails.Attribute("Value"));

问题是什么?

最佳答案

test 对象在使用前必须实例化:

TestPtr test;
test.addName(...);

或动态分配(使用new)

TestPtr* test = new TestPtr();
test->AddName(...);
//
//...
//
//And don't forget to free memory
delete test;

(在您的情况下,第一种方法更“内存安全”;))

关于c++ - 将数据插入映射变量时出现访问冲突错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35078534/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com