Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Functions with no destructor

I am writing a bare-metal C++ application that will enter an infinite loop and then never exit.

I have a number of objects that will be constructed at the top of main() and will never leave scope. Memory (both code and RAM) is at a premium, as I only have a few k-bytes to work with.

Will the optimizer generally strip out the unused destructors for me? If not, is there a way to tell the compiler not to generate any default destructors?

Also, is there an analogous way to get rid of some of the other default functions that classes come with (copy constructor etc).

like image 684
Barry Gackle Avatar asked Oct 20 '25 08:10

Barry Gackle


2 Answers

With C++11, the default destructor and some other member functions can be deleted. For a class A this can be done with.

 ~A() = delete;

That said, deleting a destructor does introduce some limitations on how an instance can be created.

For older (pre C++11) compilers, simply don't declare a destructor. While the compiler will typically create a destructor, it will often be something that is inline and does nothing - so the compiler might elect to eliminate the code entirely.

You'll also need to read your compiler documentation (or examine the code it emits) to understand what it actually does. When it comes to eliminating unused code - including deleted member functions in C++11 - you are relying on quality of implementation of your compiler. You might also find that different optimisation settings affect what it does (e.g. whether an empty inline compiler-generated destructor is actually optimised out of existence).

like image 123
Peter Avatar answered Oct 21 '25 21:10

Peter


If you are using C++11, then the default destructor can be deleted. Check the code below:

class A
{
    public:
        ~A() = delete;
};
like image 40
Nipun Talukdar Avatar answered Oct 21 '25 22:10

Nipun Talukdar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!