[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Function pointers and Optimization flag
From: |
angelo |
Subject: |
Function pointers and Optimization flag |
Date: |
17 Oct 2006 09:30:25 -0700 |
User-agent: |
G2/1.0 |
Hello, I am new to this group so hello to everybody.
I start with a problem which occur when the optimization
flag is enabled (-O1, ..., -O3) when compiling the following
code which contain function pointers. The code compile
with no problems and works correctly when no
optimization is selected. When I turn-on the optimizer,
the program produces a non-correct result. I used gcc
4.0.3 under Linux Ubuntu.
Thanks in advance for any help or suggestion.
#include <iostream>
//---------------------------------------------------------------------------
// Calc2 use a function pointer initialized at the constructor to point
to
// the selected operation.
// + No need for inheritance
// - Indirection of pointer, hard syntax
//---------------------------------------------------------------------------
class Calc2 {
public:
Calc2(const char op) {
switch(op) {
case '+' : _f = &Calc2::_add; break;
case '*' : _f = &Calc2::_mul; break;
case '/' : _f = &Calc2::_div; break;
}
}
int f(const int& a, const int& b) { (this->*_f)(a,b); }
private:
int (Calc2::*_f)(const int& a, const int& b);
int _add(const int& a, const int& b) { return (a + b); }
int _mul(const int& a, const int& b) { return (a * b); }
int _div(const int& a, const int& b) { return (a / b); }
};
// Main program
int main()
{
Calc2 calc2('+');
std::cout << calc2.f(6, 2) << std::endl;
}
- Function pointers and Optimization flag,
angelo <=