正确使用std :: move

时间:2014-05-23 10:39:29

标签: c++ pointers

以下代码有效:

class Handler {
public:
    Application* application;

    bool handle(sf::Event&);
};

class TestApp {
public:
    TestApp();

    bool running;
    void run();
    void attach_handler(Handler*);

    std::forward_list<std::unique_ptr<Handler>> handlerFList;
};

TestApp::TestApp() {
}

void Application::run() {
    while (running) {
        sf::Event event;
        while (window->pollEvent(event)) {
            for (auto& handler : handlerFList) {
                if (handler->handle(event)) {
                    break;
                }
            }
        }
    }
}

void Application::attach_handler(Handler* handler) {
    handlerFList.push_front(std::unique_ptr<Handler>(std::move(handler)));
    handler->application = this;
}

int main() {
    sqt::TestApp app;

    sqe::HandlerClose hc;
    app.attach_handler(&hc);

    app.run();
    return 0;
}

但是这个没有:

class Handler {
public:
    Application* application;

    bool handle(sf::Event&);
};

class TestApp {
public:
    TestApp();

    bool running;
    void run();
    void attach_handler(Handler*);

    std::forward_list<std::unique_ptr<Handler>> handlerFList;
};

TestApp::TestApp() {
    sqe::HandlerClose hc;
    attach_handler(&hc);
}

void TestApp::run() {
    while (running) {
        sf::Event event;
        while (window->pollEvent(event)) {
            for (auto& handler : handlerFList) {
                if (handler->handle(event)) {           // SEGFAULTS
                    break;
                }
            }
        }
    }
}

void TestApp::attach_handler(Handler* handler) {
    handlerFList.push_front(std::unique_ptr<Handler>(std::move(handler)));
    handler->application = this;
}

int main() {
    sqt::TestApp app;

    app.run();
    return 0;
}

它会在标记的地方发生。我无法弄清楚我做错了什么。是不是std :: move应该移动基础对象?看起来似乎正在发生的是,一旦TestApp的构造函数完成,该对象就会被删除。我该如何解决这个问题?

0 个答案:

没有答案