命名空间
变体
操作

std::shared_ptr<T>::unique

来自 cppreference.cn
< cpp‎ | memory‎ | shared ptr
 
 
内存管理库
(仅为说明目的*)
未初始化内存算法
(C++17)
(C++17)
(C++17)
受约束的未初始化
内存算法
C 库

分配器
内存资源
垃圾回收支持
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化存储
(直到 C++20*)
(直到 C++20*)
显式生命周期管理
 
 
bool unique() const noexcept;
(在 C++17 中弃用)
(在 C++20 中移除)

检查 *this 是否是唯一管理当前对象的 shared_ptr 实例,即 use_count() == 1

内容

[编辑] 参数

(无)

[编辑] 返回值

true 如果 *this 是唯一管理当前对象的 shared_ptr 实例,否则为 false

[编辑] 注解

此函数在 C++17 中被弃用,并在 C++20 中移除,因为 use_count() == 1 在多线程环境中没有意义(参见 注解 中的 use_count)。

[编辑] 示例

#include <iostream> 
#include <memory> 
 
int main() 
{ 
    auto sp1 = std::make_shared<int>(5);
    std::cout << std::boolalpha;
    std::cout << "sp1.unique() == " << sp1.unique() << '\n'; 
 
    std::shared_ptr<int> sp2 = sp1; 
    std::cout << "sp1.unique() == " << sp1.unique() << '\n'; 
}

输出

sp1.unique() == true
sp1.unique() == false

[编辑] 参见

返回引用到同一被管理对象的 shared_ptr 对象的数量
(公共成员函数) [编辑]