我以前没有使用过 boost,所以如果我做了一些愚蠢的事情,请原谅我。我有一个包含 lua_State 的类。我有一个 boost::shared_ptr vector ,我像这样 push_back 新状态:
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");
}
};
代码可以运行,Lua 状态已添加,但几秒钟后应用程序崩溃了。我不知道为什么会这样。当我手动执行时(没有 shared_ptrs 和手动取消引用)它工作正常。
最佳答案
您违反了 31 的规则。您创建了一个非平凡的析构函数并分配了构造函数,而没有禁用或编写复制构造函数和 operator=
.
可能在您创建 shared_ptr
时您正在复制上述类(class)。然后临时的被丢弃,事情开始繁荣。
所以,首先禁用LuaState::operator=(LuaState const&)
和 LuaState(LuaState const&)
构造函数(创建一个私有(private)的非实现版本,或者在 C++11 中 delete
它),或者实现它。
接下来,使用 make_shared<LuaState>()
创建你的 shared_ptr<LuaState>
实例。这将“就地”创建它们并删除拷贝。
1 我所说的 3 规则是什么?请参阅这些链接:Rule of Three (Wikipedia) , What is the Rule of Three?
关于c++ - 在 Boost shared_ptr 中存储多个 Lua 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13747429/