C++ 在Boost共享ptr中存储多个Lua状态

C++ 在Boost共享ptr中存储多个Lua状态,c++,pointers,boost,lua,C++,Pointers,Boost,Lua,我以前没有用过boost,所以如果我做了傻事,请原谅我。我有一个类,它拥有一个lua_状态。我有一个boost::shared_ptr向量,我将它推回新状态,如下所示: class Lua_State { lua_State *L; std::string m_scr; public: Lua_State() : L(luaL_newstate()) { lua_register(L, "test", test); luaL_openlibs(L); } ~Lua_State

我以前没有用过boost,所以如果我做了傻事,请原谅我。我有一个类,它拥有一个lua_状态。我有一个boost::shared_ptr向量,我将它推回新状态,如下所示:

class Lua_State
{
lua_State *L;
std::string m_scr;

public:
Lua_State() : L(luaL_newstate())
{
    lua_register(L, "test", test);
    luaL_openlibs(L);
}

~Lua_State() {
    lua_close(L);
}

inline bool LoadScript(const char* script)
{
    if (!boost::filesystem::exists(script))
        return false;

    m_scr = fs::path(std::string(script)).filename().string();

    chdir(fs::path(scr).parent_path().string().c_str());

    if (luaL_loadfile(L, m_scr.c_str()))
        return false;

    // prime
    if (lua_pcall(L, 0, 0, 0))
        return false;

    return true;
}
};

typedef boost::shared_ptr<Lua_State> LUASTATEPTR;
class Scripts
{
private:
std::vector<LUASTATEPTR> m_Scripts;
public:
    Scripts() { }

    void TestLoad()
{
    m_Scripts.push_back(LUASTATEPTR(new Lua_State()));
    LUASTATEPTR pState = m_Scripts[0];
    pState->LoadScript("C:/test.lua");
}
};
class Lua\u状态
{
卢厄州*L;
std::字符串m_scr;
公众:
Lua_State():L(luaL_newstate())
{
lua_寄存器(L,“测试”,测试);
luaL_openlibs(L);
}
~Lua_State(){
卢厄关闭(L);
}
内联布尔加载脚本(常量字符*脚本)
{
如果(!boost::filesystem::存在(脚本))
返回false;
m_scr=fs::path(std::string(script)).filename().string();
chdir(fs::path(scr).parent_path().string().c_str());
if(luaL_loadfile(L,m_scr.c_str())
返回false;
//主要的
if(lua_pcall(L,0,0,0))
返回false;
返回true;
}
};
typedef boost::shared_ptr luasteptr;
类脚本
{
私人:
std::向量m_脚本;
公众:
脚本(){}
void TestLoad()
{
m_Scripts.push_back(luasteptr(newlua_State());
luasteptr pState=m_脚本[0];
pState->LoadScript(“C:/test.lua”);
}
};

代码正常工作,添加了Lua状态,但几秒钟后应用程序崩溃。我不知道为什么会发生这种情况。当我手动操作时(没有共享PTR和手动取消引用),它工作正常。

您违反了规则31。您创建了一个非平凡的析构函数并分配了构造函数,而没有禁用或编写副本构造函数和
操作符=

当您创建
shared\u ptr
时,您可能正在复制上述类。然后,暂时的东西就被丢弃了,一切都变得繁荣起来

因此,首先禁用
LuaState::operator=(LuaState const&)
LuaState(LuaState const&)
构造函数(创建一个私有的非实现版本,或者在C++11
中删除它),或者实现它

接下来,使用
make_shared()
创建
shared_ptr
实例。这将“就地”创建它们并删除副本


1我所说的3的规则是什么?请查看以下链接:,

谢谢!它不再立即崩溃。该计划还有一个奇怪但相关的问题。我有2个Lua脚本,当使用std::vector单独测试时,这两个脚本都可以正常工作。如果我将这两个脚本向后推,它们都会工作大约2分钟,然后程序崩溃。当我手动运行这两个脚本时(通过手动创建两个不带std::vector的Lua_状态变量并手动“删除”它们),效果很好。我不明白为什么会发生这种事。我甚至在检查共享指针是否有效(例如if(sharedPtr){}@nicolabolas——感谢您的编辑。我用胖手指在智能手机上写的