【发布时间】:2020-04-15 07:57:19
【问题描述】:
我了解到,当您在类中使用指针时,您应该实现规则 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)) {};
};
【问题讨论】:
-
请注意,示例不会做同样的事情,因为第二个示例将隐式删除复制构造函数和赋值运算符,因为
std::unique_ptr不可复制 -
啊,这很有道理。那么我应该使用
std::shared_ptr吗? -
这取决于您是否希望
B可复制(A和B都是可移动的) -
@CiaranWelsh 这不应该是您选择智能指针类型的理由。而是:您是否需要共享所有权。在
A中没有共享所有权(至少不正确;) -
我想这是一个错字:
if (this == &other) {
标签: c++ pointers smart-pointers rule-of-three rule-of-five