C++:实现智能指针

标签 c++ smart-pointers

我正在阅读实现智能指针,我发现了以下代码,

template <class T>
class SmartPtr
{
public:
explicit SmartPtr(T* pointee) : pointee_(pointee);
SmartPtr& operator=(const SmartPtr& other);
~SmartPtr();
T& operator*() const
{
...
return *pointee_;
}
T* operator->() const
{
...
return pointee_;
}
private:
T* pointee_;
...
};

我无法理解以下内容,

  1. “SmartPtr& operator=(const SmartPtr& other)”:为什么参数是常量?分配完成后它不会失去所有权吗?
  2. 为什么我们需要“T& operator*() const”和“T* operator->() const”方法?

谢谢@

最佳答案

要点1.不一定,要看智能指针的设计。像 boost:shared_ptr 这样的东西不会在分配时转移所有权。

Point 2. 这些方法模拟了智能指针上的正常指针操作。

关于C++:实现智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11909626/

相关文章:

c++ - 库应该使用使用智能指针的接口(interface)吗?

c++ - 真正测试std::atomic是否无锁

c++ - 如何从数据库解析日期时间格式?

c++ - 将 vector<shared_ptr<Derived>> 传递给需要 vector<shared_ptr<Base>> 的函数

c++ - 使用模板函数打印智能指针 vector

c++ - 使用 unique_ptr 数据成员重载用户定义类型的 operator=

c++ - HDF5 - C++ - 打开文件读取内容失败

c++ - C++中有二次编程库吗?

c++ - gdb 远程调试缓存远程目标

销毁 CComPtr 期间的异常