Defaulted copy/move constructors/assignment operators with additional logic in body

59 views
Skip to first unread message

Will Cassella

unread,
May 20, 2015, 1:07:47 AM5/20/15
to std-pr...@isocpp.org
I ran into this issue the other day when writing a large class that needs additional book-keeping logic when being moved or copied. All fields could be copied/moved normally (just as the default versions would do), there was just a few extra function calls that needed to be made to sort things out. Whenever I added/removed fields in the class, I would have to reflect those changes in all my constructors, which became both bug-prone and a hassle. If there was a simple way to create a default move/copy constructor with some additional behavior in the body, that would be wonderful. Something along the lines of this:

MyType::MyType(const MyType& copy)
   
: default(copy)
{
   
// Additional logic
}

The constructor would then copy-construct all fields automatically, as well as running the additional code in the body. A copy-assignment operator could be implemented as such:

MyType& operator=(const MyType& copy)
{
   
if (this != &copy)
   
{
       
default(copy);
       
// Addition logic
   
}
   
return *this;
}

Both examples could be easily extended to move construction/assignment as well.

Igor Baidiuk

unread,
May 20, 2015, 9:34:29 AM5/20/15
to std-pr...@isocpp.org
You can achieve this by wrapping into protected/private structure, where all your fields are stored. Then adding default copy/move/assignment to that struct and doing desired thing in one piece.

Will Cassella

unread,
May 20, 2015, 11:52:17 AM5/20/15
to std-pr...@isocpp.org
True, but that is a rather intrusive approach simply for the sake of making the constructors easier to write; this would allow you to achieve the same effect transparently. The way I see it, this is sort of an extension of delegating constructors: delegating to default.
Reply all
Reply to author
Forward
0 new messages