I have a class called sfract
which stores a pointer to the root node of a binary tree. Obviously when copy-constructing an sfract
I need to clone the binary tree of the other sfract
object. However, the copy constructor is never called, I think because of copy elision. This causes two sfract
objects to refer to, and attempt to deallocate, the same root node on deconstruction. How can I prevent this from happening?
//main.cpp
sfract_type a( /*...*/ );
sfract_type b( /*...*/ );
sfract_type c( a ); // copy construct
//sfract.h
template< class FType, class Alloc >
sfract( sfract< FType, Alloc > const & other )
{
// Clone other's root node and assign to this object
root = other.root->clone();
}
I cannot see your code, but your templated constructor is not going to take precedence over the default copy constructor, and therefore in the case where FType and Alloc match that of your class, the default one will be invoked.
You have two options:
And of course because you are overloading your copy-constructor ensure your assignment operators are also correctly handled (as well as the destructor).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With