有了NotCopyable之后,怎样才能让Student不支持复制呢?大家还记得编译器生成默认的复制构造函数和赋值操作符重载的规则吗?如果父类不存在这些函数的话,那么子类默认也不会生成。那么最简单的做法就是让Student去继承自NotCopyable

代码

#include <cstdlib>
#include <string>

using namespace std;

class NotCopyable {
    NotCopyable() = default;
    NotCopyable(const NotCopyable &) = delete;
    NotCopyable(NotCopyable &&) = delete;
    NotCopyable& operator=(const NotCopyable &) = delete;
    NotCopyable& operator=(NotCopyable &&) = delete;
};

struct Student : private NotCopyable
{
    string name;
    time_t birtyday;
};

int main()
{
    Student a;
    Student b = a;
    a = b;
    return 0;
}