Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent copy elision?

Tags:

c++

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();
}
like image 501
PeddleSpam Avatar asked Mar 22 '23 02:03

PeddleSpam


1 Answers

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:

  1. Overload that too.
  2. Derive your template (possibly protected) from a non-templated base class that manages that part of the copy/clone. That can often be better as you have a single class managing the "root" member.

And of course because you are overloading your copy-constructor ensure your assignment operators are also correctly handled (as well as the destructor).

like image 129
CashCow Avatar answered Apr 02 '23 01:04

CashCow