Rule of Three in C++

后端 未结 3 1341
一生所求
一生所求 2020-12-07 03:43

I\'ve read that The Rule of Three, What is The Rule of Three? is summarized as follows:

If you need to explicitly declare either the destructor, copy

3条回答
  •  情话喂你
    2020-12-07 04:23

    If you know that the copy constructor won't be used, you can express that by making it private and unimplemented, thus:

    class C
    {
    private:
        C(const C&); // not implemented
    };
    

    (in C++11 you can use the new = delete syntax). That said, you should only do that if you're absolutely sure it will never be needed. Otherwise, you might be better off implementing it. It's important not to just leave it as is, as in that case the compiler will provide a default memberwise copy constructor that will do the wrong thing - it's a problem waiting to happen.

    To some extent it depends on what the class is going to be used for - if you're writing a class that's part of a library, for instance, it makes much more sense to implement the copy constructor for consistency reasons. You have no idea a priori how your class is going to be used.

提交回复
热议问题