std::map.clear() 引发读取访问冲突

std::map.clear() is throwing an Read Access Violation

我试图在 std::map 上调用 clear() 方法而没有得到“异常抛出:读访问 violation._Pnode 是 0xDDDDDDDD.".

//I have narrowed down the error to this group of code
#include "stdafx.h"
#include <map>
#include <iostream>

class Input
{
    std::map<int, bool> pressedKeys;
    std::map<int, bool> heldKeys;
    std::map<int, bool> releasedKeys;

public:
    void Update()
    {
        heldKeys.clear();
        pressedKeys.clear();
        releasedKeys.clear();
    }
};

class Window
{
private:
    Input * input;
    void Update()
    {
        input->Update();
    }
public:
    Window()
    {
        input = &Input();

        while (true)
        {
            this->Update();
        }
    }
};

int main()
{
    Window w = Window();
}

异常总是发生在 "heldKeys.clear();" Visual Studio 中的调试器将我带到一个名为 "xtree." 的页面下面的代码是 "xtree:"

中发生异常的代码
void _Erase(_Nodeptr _Rootnode)
    {   // free entire subtree, recursively
    for (_Nodeptr _Pnode = _Rootnode; !_Pnode->_Isnil; _Rootnode = _Pnode) //The error occurs here
        {   // free subtrees, then node
        _Erase(_Pnode->_Right);
        _Pnode = _Pnode->_Left;
        _Alnode& _Al = this->_Getal();
        _Alnode_traits::destroy(_Al, _STD addressof(_Rootnode->_Myval));
        _Node::_Freenode0(_Al, _Rootnode);
        }
    }

我希望没有例外。 我收到异常“抛出异常:读取访问冲突。 _Pnode 是 0xDDDDDDDD." 如果需要更多说明,请发表评论。

您的编译器是否打开了所有警告?实际上,任何相当新近的高质量 C++ 编译器都应该捕捉到这一点。例如。转到 http://rextester.com/l/cpp_online_compiler_clang 并输入代码,删除无论如何都不需要的 stdafx.h header,您会看到:

source_file.cpp:31:17: error: taking the address of a temporary object of type 'Input' [-Waddress-of-temporary]
        input = &Input();
                ^~~~~~~~

(使用 clang 3.8 作为编译器。)

与 Stack Overflow 相比,这证明了一种更有效的方法来查找 class 的 run-of-the-mill 编程错误。其他 class 错误可能涉及打开额外的分析通道或清理器,例如 clang 的地址清理器、内存清理器或未定义的行为清理器。