jeudi 24 janvier 2019

Why can't the copy-and-swap idiom for copy-assignment be generated automatically, when a copy-constructor is supplied?

I have been reading up on the Rule of Three and the Copy&Swap Idiom. The latter made me wonder: Why don't compilers generate the copy&swap idiom automatically, if a copy-constructor is supplied?

Naively, it would seem that implementing the copy-constructor (and destructor) should be enough, if explicit declaration of a copy-constructor implied use of the copy-and-swap idiom for assignment, with "Swap" being defined as dumb bit-wise swap of the objects.

So I was wondering: What prevents compilers from supplying a default copy-and-swap implementation for copy-assignment, when the user has supplied a copy constructor?

The thread What is The Rule of Three? was given as duplicate of at least an earlier revision of my question. And while its answers explain the Rule of Three and that most programmers should rather stick to the Rule of Zero by using modern STL constructs, it doesn't explain why the copy-and-swap pattern is not or maybe cannot be generated automatically.

Aucun commentaire:

Enregistrer un commentaire