我正在编写一个函数来将某个特定类(二维直方图TH2F*
)的内容复制到另一个TH2F*
. 实际上,我希望能够做到
SafeCopy( in, out )
in
我的输入在哪里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 指针。在后一种情况下,会发生一些奇怪的事情:如果我调用 SafeCopy 并传递一个 NULL h_out 我会得到以下输出:
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 );