我了解到,当您在类中使用指针时,您应该实现规则 5。如果您不使用指针,那么您可以,实际上更可取的是使用默认值。但是,这如何与智能指针一起使用?例如,包含 的类int*
可能如下所示:
class A {
private:
int *num_;
public:
explicit A(int* num) : num_(num) {}
~A() {
delete num_;
}
A(const A &other) {
if (this != &other) {
num_ = other.num_;
}
}
A(A &&other) noexcept {
if (this != &other) {
num_ = other.num_;
}
}
A &operator=(A &other) {
if (this == &other) {
this->num_ = other.num_;
}
return *this;
}
A &operator=(A &&other) noexcept {
if (this == &other) {
this->num_ = other.num_;
}
return *this;
};
};
但是如果我们使用智能指针,这样做就足够了吗?
class B {
private:
std::unique_ptr<int> num_;
public:
explicit B(int num) : num_(std::make_unique<int>(num)) {};
};