Jav*_* Mr 4 c c++ malloc lua new-operator
当从C malloc保留内存时,应该如何使用c ++类?
我正在使用一个C库(lua),我需要向它公开一个C++类,在这种情况下,为了垃圾收集这些保留空间,lua进行内存预留.
下面是一个更简单的类似场景:
#include <string>
class Clase{
private:
std::string valor;
public:
Clase(){}
Clase(const std::string & valor) : valor(valor){}
const std::string & get() const { return this->valor; }
void set(const std::string & valor){ this->valor = valor;}
~Clase(){}
};
typedef struct
{
Clase cls;
}Estructura;
int main(int argc, char ** argv)
{
Estructura * est = (Estructura *) malloc(sizeof(Estructura));
est->cls.set("Hola"); // First attempt
Clase myCls; // Second attempt
est->cls = myCls;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我理解并检查过,使用malloc不会调用类构造函数; 这是预期的,因此无法使用无效实例(Class中的字符串)调用copy(assign)运算符.我怀疑在Class实例中复制字符串时,第二次尝试在同一点失败.
所以:
在Estructura中使用Clase指针,效果很好,这是最好的解决方案吗?
作为奖励,当lua垃圾收集它时删除实例的最佳方法是?使用__gc元方法还是更好的东西?
Sea*_*ean 10
这是一个有点奇怪使用malloc,而不是new,但它是可能的.您需要使用新的展示位置:
void *memory = malloc(sizeof(Estructura));
Estructura *est = new(memory)Estructura;
Run Code Online (Sandbox Code Playgroud)
当你完成对象后,你自己有责任自己调用析构函数:
est->~Estructura();
Run Code Online (Sandbox Code Playgroud)
所有东西,比如vtable,都会被正确初始化,所以不用担心.尴尬的一点是处理删除,因为你需要在释放内存之前破坏对象free.delete这会自动为你做,但你需要自己做.