CodeWeed
CodeWeed

Reputation: 1071

Optimization of C++ program

I have the given program ? Can the output of the main function vary depending on the optimizer ?

1) Can the optimizer call the destructor of 'a' after the line# 19

2) At line# 17, Can this line be optimized away by any optimizer, since it not referenced anywhere in main ? or is it has any dependency on the static variable in the class ?

3) Again about line # 17, is it possible that the Optimizer initializes the array objects and destruct them straight away, because of 'b' is not used ?

 1.    class Test 
 2.    {
 3.        public:
 4.        static int n;
 5.        Test()
 6.        {
 7.            n++;
 8.        }
 9.        ~Test()
10.        {
11.            n--;
12.        }
13.    } 
14.    int main()
15.    { 
16.        Test a;
17.        Test b[5];                             
18.        Test *c = new Test;
19.        std::cout << a.n << std::endl;         
20.        delete c;
21.        std::cout << Test::n << std::endl;
22.        return 0;
23.    }

Upvotes: 1

Views: 138

Answers (1)

Bathsheba
Bathsheba

Reputation: 234635

The optimiser is allowed to do anything so long as (i) the standard is followed and (ii) there are no side effects in making the optimisation.

Since your destructor has a side effect (the decrement of n), then it must be called in the right place. In particular a must be destroyed after c is deleted.

Note that in production you'd want to use an atomic type for n: your code at present is not thread safe.

Also note that your declaration of main is incorrect. You must use int main() or the version with the command line arguments. Technically the behaviour of your program is undefined.

Upvotes: 4

Related Questions