Arduino C++ destructor?

2019-08-09 03:45发布

问题:

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?

回答1:

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.



回答2:

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);
}


标签: c++ arduino