scarsty / kys-cpp

《金庸群侠传》c++复刻版,已完工
BSD 3-Clause "New" or "Revised" License
2.57k stars 370 forks source link

shared_ptr/unique_ptr 区别是什么? #73

Closed zchrissirhcz closed 11 months ago

zchrissirhcz commented 11 months ago

查看并修改了 src/Application.cpp 文件中, 变量 s 的定义。在修改 s 定义之前,已能够正常运行 (ubuntu 22.04, 使用 game21 目录的资源).


int Application::run()
{
    auto engine = Engine::getInstance();
    engine->setStartWindowSize(1280, 720);
    engine->init();    //引擎初始化之后才能创建纹理
    engine->createAssistTexture(800, 450);

    config();

    //开始界面
    //auto s = std::make_shared<TitleScene>();    // ok
    //auto s = std::make_unique<TitleScene>();    // crash
    //std::shared_ptr<TitleScene> s(new TitleScene); // ok
    std::unique_ptr<TitleScene> s(new TitleScene); // crash

    s->run();

    return 0;
}

对应的报错信息:

MoneyItemID = 174
CompassItemID = 182
terminate called after throwing an instance of 'std::bad_weak_ptr'
  what():  bad_weak_ptr
zsh: IOT instruction (core dumped)  ./kys

疑问: 此处 s 变量没有被拷贝使用,为啥不能用 unique_ptr ?