C++ > インライン関数

インライン関数(inline function)の特徴

  • 仮引数付きマクロに近いもの。インライン関数が呼び出された場合、その部分が置き換えられる。
  • 関数呼び出しに伴うオーバーヘッドを削減できる。
  • 一方で呼び出す回数が多いとプログラムが肥大化するため、インライン関数は短いものに限る。
  • インライン関数はコンパイラに対してコマンドではなく要求である。要求が実行できない場合は通常の関数としてコンパイルされる。つまり、インライン化されない。 例)static変数、ループ文、switch文、goto文、再帰

インライン関数の呼び出し

 関数定義の前にinline指定子を付ける 例)

#include <iostream>
using namespace std;

inline int even( int x )
{
  return !( x % 2 );
}

int main()
{
  if( even( 10 ) ){
    cout << "10 is even" << endl;
  }
  if( even( 11 ) ) {
    cout << "11 is odd" << endl;
  }

  return 0;
}

自動インライン化

  • クラス定義内でインライン関数を定義する場合、inlineキーワードは不要となる。
  • クラス定義内には数行にわたって書くこともできるが、簡潔に一行で書かれることのほうが多い。
  • 他の場所で定義してはいけない。 例)
    #include <iostream>
    using namespace std;
    
    class samp {
      int i,j;
    public:
      samp( int a, int b );
      //defined here,divisible() inlined automatically
      int divisible(){ return !( i % j ); }
    };
    
    samp::samp( int a, int b )
    {
      i = a;
      j = b;
    }
    
    int main()
    {
      samp ob1( 10, 2 );
      samp ob2( 10, 3 );
    
      if( ob1.divisible() ){
        cout << "10 is divisible by 2" << endl;
      }
    
      if( ob2.divisible() ){
        cout << "10 is divisible by 3" << endl;
      }
    
      return 0;
    }

インラインコンストラクタ

コンストラクタ、デストラクタをインラインで定義できる。 例)

#include <iostream>
using namespace std;

class samp {
  int i,j;
public:
  //inline constructor
  samp( int a, int b ){ i = a; j = b; }
   int divisible(){ return !( i % j ); }
};


参考文献

  • 独習C++ 第3版(Herbert Schildt,2002,翔泳社)
最終更新:2011年03月04日 14:10