我有时会遇到内存访问冲突错误....
但我不知道错误来自哪里......
所以我查看了代码,发现了一些奇怪的代码......
delete m_p1;
A *a = new A();
a->b = *c;
m_p1 = a; --> strange code.
Run Code Online (Sandbox Code Playgroud)
我认为这有点奇怪......我可以在删除m_p1之后使用m_p1吗?
它可以使一些内存访问错误?
你在Windows上.
这意味着如果在安装了Visual Studio的计算机上发生错误,您可以选择打开它来调试错误,从而知道错误发生的确切行.
代码太少无法正确回答.人们可以猜测:
delete m_p1;
Run Code Online (Sandbox Code Playgroud)
你确定m_p1是一个指向有效对象的指针吗?(分配new等)
A *a = new A();
Run Code Online (Sandbox Code Playgroud)
你必须检查A的构造函数.也许它做错了.
a->b = *c;
Run Code Online (Sandbox Code Playgroud)
This is the line I suspect the more : If c is an invalid pointer (either NULL, or points to some random address), dereferencing it to put the result inside a->b could provoke the error
m_p1 = a; --> strange code.
Run Code Online (Sandbox Code Playgroud)
The funny fact is that this is the only line of code which can't produce the error you got : a is a pointer containing an address, and you can copy addresses around. It's using this address (dereferencing the pointer, etc.) that causes memory access violation.
m_p1 = a;This code is not so strange, but it proves you still have issues with pointers.
在C,C++,Java等中,当你分配一个内存(把东西放进去,创建一个对象等)时,分配器(new,malloc,等等......)会给你一个句柄.在Java/C#中,这称为引用,在C/C++中,这是一个指针.
让我们想象一下你会去参加一场音乐会,座位号是你坐的地方,这seat是真实的物体,你可以坐下来享受这个节目.
m_p1是你钱包里的一张纸,你想要准确的座位号码a 是一张临时纸,一张餐巾纸,不管......delete m_p1当你转售你的地方时,你之前购买的座位号码不再有效.你不应该再使用它了.a = new A()是当你买另一个地方,所以你有a另一个有效的座位号码,但无论出于何种原因m_p1,你不会写在你的钱包里(),你会把它写在餐巾纸上.m_p1 = a 是你最终将座位号码从一些餐巾纸复制到你的钱包里.关键是你有:
通过销毁真实对象delete不会破坏指针.它只会使地址无效(地址没有改变.它只是无效了).因此,您可以将指针放入指针,甚至可以重用指针来包含另一个对象的地址.