Why is std::shared_ptr::unique() deprecated?

后端 未结 3 1343
误落风尘
误落风尘 2021-02-03 20:42

What is the technical problem with std::shared_ptr::unique() that is the reason for its deprecation in C++17?

According to cppreference.com, std::shar

3条回答
  •  庸人自扰
    2021-02-03 21:28

    Consider the following code:

    // global variable
    std::shared_ptr s = std::make_shared();
    
    // thread 1
    if (s && s.unique()) {
        // modify *s
    }
    
    // thread 2
    auto s2 = s;
    

    Here we have a classic race condition: s2 may (or may not) be created as a copy of s in thread 2 while thread 1 is inside the if.

    The unique() == true means that no one has a shared_ptr pointing to the same memory, but does not mean any other threads have no access to initial shared_ptr directly or through pointers or references.

提交回复
热议问题