我正在编写一个函数来将某个特定类的内容(一个二维直方图,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 );
答案 0 :(得分:0)
您尚未显示调用代码,但听起来问题来自SafeCopy(something, NULL)
之类的问题。是的,不行。传入指针并返回结果:
TH2F *SafeCopy(constTH2F *in, TH2F *out) {
if (!out)
out = whatever;
*out = *in; // or whatever...
return out;
}
答案 1 :(得分:0)
如果我调用SafeCopy传递NULL h_out,我得到这个输出:
...
*编辑这是主叫代码:
TH2F * h_smearedMigration;
...
SmartCopy(h_migration,h_smearedMigration);
这不是一个NULL指针,这是一个未初始化的指针。它包含随机垃圾,不太可能是0x0。
答案 2 :(得分:0)
首先,目前尚不清楚为什么要使用指针。理想情况下,您只想直接保存对象。然后,您不需要特殊的复制约定:
TH2F RunToy(TH2F const &in);
//TH2F h_migration is created and filled previously in the program
for (int ntoy=0; ntoy < NTOY; ntoy++ ) {
TH2F h_smearedMigration = RunToy(h_migration);
如果TH2F
复制起来很昂贵,那么你可以通过像pImple之类的东西来实现它,这样它移动起来便宜但仍然像值类型一样。
如果你确实需要指针,那么你应该使用智能指针并且从不拥有原始指针(例如,拥有原始指针几乎可以保证你的代码异常 - 不安全)。
void RunToy(std::unique_ptr<TH2F> in_out);
void SafeCopy(TH2F const &in, std::unique_ptr<TH2F> &out)
{
if(h_out) {
*out = in; // copy assignment
} else {
out = make_unique<TH2F>(h_in); // copy construction
}
}
for (int ntoy=0; ntoy < NTOY; ntoy++ ) {
std::unique_ptr<TH2F> h_smearedMigration;
SmartCopy(h_migration, h_smearedMigration);
RunToy(h_smearedMigration );
当然,您通常不需要SmartCopy
函数来动态确定是使用复制赋值还是复制构造。根据您是否已经分配了对象,您应该知道自己需要什么。
// std::unique_ptr<TH2F> h_migration is created and filled previously in the program
for (int ntoy=0; ntoy < NTOY; ntoy++ ) {
auto h_smearedMigration = make_unique<TH2F>(*h_migration);
RunToy(h_smearedMigration);