不知何故,我需要在预先分配的内存中使用类对象。然而,g++ 不喜欢我下面的代码。它说的是
第 26 行中“CTest::CTest”的使用无效
如何更改它以使其正常工作?
#include <stdio.h>
#include <stdlib.h>
#include <string>
class CTest
{
public:
CTest(const char* str)
{
printf("constructor\n");
m_str = str;
}
virtual ~CTest()
{
printf("destructor\n");
}
void output()
{
printf("output:%s\n", m_str.c_str());
}
protected:
std::string m_str;
};
struct TTT
{
char test_ptr[sizeof(CTest)];
};
int main(int argc, char* argv[])
{
struct TTT* ttt = (struct TTT*)malloc(sizeof(struct TTT));
CTest* test = (CTest*)(ttt->test_ptr);
test->CTest("123456");
test->output();
test->~CTest();
return 0;
}
最佳答案
您不能直接调用构造函数。相反,您必须对对象使用“placement new”( What uses are there for "placement new"? )。它基本上使用您提供的内存来调用构造函数。但是,您可以直接调用析构函数——简单地调用 ~CTest() 并且不调用删除。
关于c++ - 我可以显式调用类的构造函数和析构函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22333097/