C++高频面试题 | 你能实现一个简易的C++智能指针吗?
在C++相关的秋招面试中,经常问被要求实现一个简易的C++智能指针。
我自己去年秋招的时候也多次要求实现。在此,提供一个实现。
更多硬核知识,vx搜一搜:
look_code_art,更多硬核等你发现,
也可以添加个人 vx:fibonaccii_,有很多小伙伴一起准备秋招
代码如下:
// RAII 技术封装
class RefCount {
public:
RefCount() : reference_{0}
{ }
~RefCount() {
this->decrementRef();
}
void IncrementRef()
{
++reference_;
}
bool decrementRef()
{
if (--reference_ == 0) {
delete this;
return true;
}
return false;
}
int64_t use_count() {
return reference_;
}
private:
std::atomic<int64_t> reference_;
};
template <typename T>
class SharedPtr
{
public:
SharedPtr() : ptr_(nullptr) {}
explicit SharedPtr(T* ptr)
: ptr_(ptr),
ref_(new RefCount)
{
if (ref_) ref_->IncrementRef();
}
SharedPtr(const SharedPtr& other)
: ptr_(other.ptr_),
ref_(other.ref_)
{
if (ref_) ref_->IncrementRef();
}
SharedPtr(SharedPtr&& other) noexcept {
ptr_ = other.ptr_;
ref_ = other.ref_;
other.ptr_ = nullptr;
other.ref_ = nullptr;
}
SharedPtr& operator=(const SharedPtr& other) {
if (this == &other || *this == other)
return *this;
reset();
ptr_ = other.ptr_;
ref_ = other.ref_;
ref_->IncrementRef();
return *this;
}
SharedPtr& operator=(SharedPtr&& other) noexcept {
if (this == &other || *this == other) return *this;
reset();
ptr_ = other.ptr_;
ref_ = other.ref_;
other.ptr_ = nullptr;
other.ref_ = nullptr;
return *this;
}
~SharedPtr()
{
if (ref_) this->decrementRef();
}
T& operator*() const { return *ptr_; }
T* operator->() const { return ptr_; }
explicit operator bool() const { return !!ptr_; }
T* get() const { return ptr_; }
void reset() {
if (ptr_) {
this->decrementRef();
// ptr_ = nullptr;
}
}
void decrementRef() {
if(ref_ && ptr_) {
if(ref_->decrementRef()) {
delete ptr_;
ptr_ = nullptr;
}
}
}
int64_t use_count() {
return ref_->use_count();
}
bool unique() {
return use_count() == 1;
}
void swap(SharedPtr & other) {
std::swap(ptr_, other.ptr_);
std::swap(ref_, other.ref_);
}
friend inline bool operator==(SharedPtr const& lhs, SharedPtr const& rhs) {
return lhs.ptr_ == rhs.ptr_;
}
friend inline bool operator!=(SharedPtr const& lhs, SharedPtr const& rhs) {
return lhs.ptr_ != rhs.ptr_;
}
friend inline bool operator<(SharedPtr const& lhs, SharedPtr const& rhs) {
return lhs.ptr_ < rhs.ptr_;
}
private:
T* ptr_;
RefCount* ref_;
};
int main(int argc, char const *argv[]) {
SharedPtr<int> iptr (new int);
SharedPtr<int> iptr2(iptr);
SharedPtr<int> iptr3(std::move(iptr));
SharedPtr<int> iptr4 = iptr2;
SharedPtr<int> iptr5 = std::move(iptr3);
std::cout<<iptr5.use_count()<<std::endl; // 3
return 0;
} #C/C++##学习路径#