Pwnna
Pwnna

Reputation: 9538

Arduino C++ destructor?

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?

Upvotes: 3

Views: 12559

Answers (3)

Daniel De León
Daniel De León

Reputation: 13679

Sorry but you can use delete in Arduino with anything that's created with new.

And the destructor is called when you deleted.

And Yes about malloc and free.

class MyClass {
  private:
    char *_var;
  public:
    MyClass(int size) { // Constructor
      _var = (char *) malloc(sizeof(char) * size);
      ...
    }

  ~MyClass() { // Destructor
    free( _var );
  }
  ...
}

Upvotes: 0

Lol4t0
Lol4t0

Reputation: 12547

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

Upvotes: 1

aambrozkiewicz
aambrozkiewicz

Reputation: 552

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.

Upvotes: 2

Related Questions