类与对象R-2-1-1强制

禁止含动态分配成员的类省略拷贝构造函数和赋值操作符

未编写拷贝构造函数和赋值操作符
test.cpp
1class Foo
禁止含动态分配成员的类省略拷贝构造函数和赋值操作符 [gjb8114-r-2-1-1]
2{
3 int *ptr;
4public:
5 Foo();
6 ~Foo();
7};
8
9Foo::Foo() : ptr(new int(0)) {}
10
11Foo::~Foo() { delete ptr; }
已编写拷贝构造函数和赋值操作符
test.cpp
1class Foo
2{
3 int *ptr;
4public:
5 Foo();
6 ~Foo();
7 Foo(const Foo &other);
8 Foo &operator=(const Foo &rhs);
9};
10
11Foo::Foo() : ptr(new int(0)) {}
12
13Foo::~Foo() { delete ptr; }
14
15Foo::Foo(const Foo &other) : ptr(new int(*other.ptr)) {}
16
17Foo &Foo::operator=(const Foo &rhs)
18{
19 if (this != &rhs)
20 *ptr = *rhs.ptr;
21 return *this;
22}