我对 C++ 很陌生,我一直在玩弄 指针和类有点。到目前为止我遇到了一个问题 我一直无法找到解决方案:
Unhandled exception at 0x77F87508 (msvcr110d.dll) in RAII.exe: 0xC0000005: Access violation reading location 0xCCCCCCC0.
好像跟我访问指针有关系 我无权访问。
主要.cpp:
#include <memory>
#include <iostream>
#include "Example.hpp"
void example()
{
Example e;
}
int main()
{
example();
std::cout << "Press any key to exit";
std::cin.get();
return 0;
}
例子.cpp:
#include "Example.hpp"
Example::Example()
{
m_a = new int(1);
m_b = new int(2);
m_b = new int(3);
}
Example::~Example()
{
delete m_a;
delete m_b;
delete m_c;
}
例子.hpp:
#ifndef _EXAMPLE_HPP_
#define _EXAMPLE_HPP_
#include <memory>
#include <iostream>
class Example
{
private:
int *m_a;
int *m_b;
int *m_c;
public:
Example();
~Example();
};
#endif _EXAMPLE_HPP_
所以,我基本上做的是在 构造函数并在析构函数中释放它。
欢迎任何帮助!提前致谢:D
最佳答案
你的代码有错误:
Example::Example()
{
m_a = new int(1);
m_b = new int(2);
m_b = new int(3); // <--- you probably meant it to be m_c
}
因此,当您在析构函数中调用 delete m_c;
时,您最终会释放不属于您的应用程序的内存,因此会遇到崩溃。
关于c++ - 类(class)访问违规阅读位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15991687/