Is the copy and swap idiom still useful in C++11

后端 未结 4 800
轮回少年
轮回少年 2020-12-24 14:16

I refer to this question: What is the copy-and-swap idiom?

Effectively, the above answer leads to the following implementation:

class MyClass
{
publi         


        
4条回答
  •  悲哀的现实
    2020-12-24 15:08

    You're certainly not considering the whole picture. Your code re-uses constructors for different assignment operators, the original re-uses assignment operators for different constructors. This is basically the same thing, all you've done is shift it around.

    Except that since they write constructors, they can deal with non-default-constructible types or types whose values are bad if not initialized explicitly like int or are plain expensive to default-construct or where the default-constructed members are not valid to destruct (for example, consider a smart pointer- an uninitialized T* leads to a bad delete).

    So basically, all you've achieved is the same principle but in a decidedly worse place. Oh, and you had to define all four functions, else mutual recursion, whereas the original copy-and-swap only defined three functions.

提交回复
热议问题