c++ - 我可以显式调用类的构造函数和析构函数吗?

标签 c++ constructor g++ destructor

不知何故,我需要在预先分配的内存中使用类对象。然而,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/

相关文章:

c++ - 一个函数指针,指向一个函数,该函数采用模板类的对象,并将所述函数指针作为模板参数。可能的?

c++ - 使用CRTP和Google测试框架的库API

javascript - 不能通过 Babel 的 transform-class-properties 在父类构造函数中使用子类的属性

c++ - glfwWindowHint 错误

c++ - C++/编译: is it possible to set the size of the vptr (global vtable + 2 bytes index)

c++ - G++ 忽略 _Pragma 诊断被忽略

C++ 编译陷入 boost interprocess lib 'error: `::ftruncate' 尚未声明'

c++ - 有没有办法定义和发送单个 BIT

c# - 有没有办法在构造函数中初始化 EII 属性?

JavaScript new Function 表达式和 new Function 构造函数