C++ 智能指针、算法及函数传递详解
1. 智能指针操作
智能指针在 C++ 中是管理动态内存的重要工具,下面介绍 shared_ptr<T> 和 weak_ptr<T> 的相关操作。
1.1 shared_ptr<T> 的比较与检查
shared_ptr<T> 可以使用比较运算符来比较其包含的地址。例如,比较两个 shared_ptr<T> 对象 pA 和 pB 是否指向同一对象:
if((pA == pB) && (pA != nullptr))
std::cout << " Both pointers point to the same object.\n";
由于两个指针可能都为 nullptr 且相等,所以简单比较不能确定它们指向同一对象。 shared_ptr<T> 可隐式转换为 bool 类型,因此上述代码也可写成:
if(pA && (pA == pB))
std::cout << " Both pointers point to the sam
超级会员免费看
订阅专栏 解锁全文
3万+

被折叠的 条评论
为什么被折叠?



