日曜日, 5月 19, 2013

C++ - Voidポインタを活用

Voidポインタの役割

Voidポインタはあらゆる型でありえるメモリロケーションを指し示すポインタである.Genericポインタは指定された型Tのみをストアできるポインタできるという点でVoidポインタでは異なる.
Voidポインタは非常に便利だが,Voidポインタを多用しているならばそれはかなり投げやりなインターフェースデザインか,かなり極端なグランドデザインに走っていると考えたほうが良い.

つかいどころ

相当程度に万能な関数を定義する際に使うことがあるだろうか.相当緩やかな契約を提供してもよいストラテジーパターンを取るときも使ってもよいだろう.voidポインタが使われている最も有名なところはpthreadのパラメータ.

サンプル

上述したとおり,付き合い方のツボをきちんと押さえていれば,voidポインタは非常に強力なあなたの味方である.以下の例はvoidパラメータをとる異なる2つの関数をポインタ経由で呼び出している例.

#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;

void ShowIntVal(void* param);
void ShowValFromVector(void* param);

void (*pShowValFunc)(void* param);

int main() {

 // int val
 pShowValFunc = ShowIntVal;
 int val = 32;
 pShowValFunc((void*)&val);
 vector<int> v;
 v.push_back(-20);
 v.push_back(-2000);
 pShowValFunc = ShowValFromVector;
 pShowValFunc((void*)&v);

 return EXIT_SUCCESS;

}

void ShowIntVal(void* param){

 int* pIntVal = static_cast<int*>(param);
 cout << "ShowIntVal:" << *pIntVal << endl;

}

void ShowValFromVector(void* param){

 vector<int> *pV = static_cast<vector<int>*>(param);
 vector<int>::iterator iter;
 cout << "ShowValFromVector:";
 for( iter = pV->begin(); iter != pV->end();iter++)
  cout << *iter << ' ';
 cout << endl;

}



0 件のコメント: