Arduino C++ destructor?

2019-08-09 03:24发布

I know that in Arduino you can't use delete. So when does the destructor defined in C++ classes gets called?

Similarly, if I want to create a pointer to array, I would have to use malloc and free?

标签: c++ arduino
2条回答
叛逆
2楼-- · 2019-08-09 03:52

The destructor is called when the object is destroyed. For automatic (on stack) variables, it's called after leaving its scope ({}). Read more about automatic variables.

查看更多
不美不萌又怎样
3楼-- · 2019-08-09 03:53

The destructor gets called when the variable goes out of scope or delete'd. This means, if you have no delete you can only create non-POD structures in automatic memory.

You cannot use malloc and free, because constructors and destructors will not be called.

But, you can try create your own new and delete like this:

void* operator new(size_t size)
{
    void* mem = malloc(size);
    if (!mem) {
        throw std::bad_alloc();
    }
    return mem;
}

void operator delete(void* ptr)
{
    free(ptr);
}

void* operator new[] (size_t size)
{
    return (operator new)(size);
}

void operator delete[](void* ptr)
{
    return (operator delete)(ptr);
}
查看更多
登录 后发表回答