特定のクラス (2D ヒストグラムTH2F*
) の内容を別のクラスにコピーする関数を作成していTH2F*
ます。実際には、私はできるようになりたいです
SafeCopy( in, out )
wherein
は私の入力TH2F*
でout
あり、私の目的地TH2F*
です。特に、事前に割り当てられていないSafeCopy
場合でも動作できるように実装したいと考えています。out
最初の例では、この(間違った)方法で関数を実装しました
void SafeCopy( const TH2F * h_in, TH2F *h_out )
{
cout << "SafeCopy2d: output histogram address is " << h_out << endl;
if( h_out != NULL )
{
cout << "SafeCopy2d: h_out has been identified as non-zero pointer\n";
(*h_out) = *h_in; // I'm making use of the copy-constructor
// it wouldn't work if h_out == NULL
}
else
{
cout << "SafeCopy2d: h_out has been identified as null pointer\n";
h_out = new TH2F( *h_in );
cout << "SafeCopy2d: h_out address is now " << h_out << endl;
}
}
そして出力は
SafeCopy2d: output histogram address is 0x0
SafeCopy2d: h_out has been identified as null pointer
SafeCopy2d: h_out address is now 0xblahblah
しかし、もちろんこれは機能しませんでした。関数を終了するとき、参照ではなくコピーで渡したため、「実際の」ポインター h_out がまだ 0 だったからです。次に、関数のプロトタイプを(実装を変更せずに)変更しました
void SafeCopy( const TH2F * h_in, TH2F *&h_out )
h_out ポインターを参照で渡すため。この後者の場合、何か奇妙なことが起こります。NULL h_out を渡して SafeCopy を呼び出すと、次の出力が得られます。
SafeCopy2d: output histogram address is 0x*a non-zero value*
SafeCopy2d: h_out has been identified as non-zero pointer
私の質問は、h_out をコピーで渡すと、NULL ポインターとして正しく認識されるのに、参照で渡すと非ゼロとして表示されるのはなぜですか?
編集 これは呼び出しコードです:
//TH2F * h_migration is created and filled previously in the program
TH2F * h_smearedMigration;//
for (int ntoy=0; ntoy < NTOY; ntoy++ ) {
//matrix smearing
SmartCopy( h_migration, h_smearedMigration ); //copy the original matrix to a temporary one
RunToy( h_smearedMigration ); //smear the matrix
...
みたいなことは避けたい
h_smearedMigration = SmartCopy( h_migration, h_smearedMigration );