I have a situation where I have the following, briefly:
class K {
K clone() const{K cl; /* clone this to cl then */ return cl; }
};
K* call_clone()
{
K k;
return new K(k.clone());
}
after compiler optimization, will this be doubly copied?
Alternatively:
Would be an implementation with C*clone() more efficient?
Like this:
class K {
K* clone() const { K*p=new K(); /* clone this to *p then */ return p; }
};
K* call_clone()
{
K k;
return k.clone();
}
(I ask this because even a shallow copy of K could be costly, it will be a class data struct in practice.)
It depends upon the compiler. Any modern compiler will not perform a double copy, this is called a Return Value Optimization. It does not depend on whether the definition of
clone()is available or not.No, it won’t. Dynamic memory management (operators new/delete and alike) are very expensive. It might be even more expensive than performing a double-copy, depending on what your copy-constructor actually does.