template<classT>classweak_ptr; (C++11 起) std::weak_ptr是一种智能指针,它持有被std::shared_ptr管理的对象的非拥有性“弱”引用。在访问引用的对象前必须先转换为std::shared_ptr。 std::weak_ptr实现临时所有权:当某个对象只有存在时才需要被访问,且随时可能被他人删除时,可以使用std::weak_ptr来跟踪...
std::weak_ptr<T>::weak_ptr constexprweak_ptr()noexcept; (1)(since C++11) weak_ptr(constweak_ptr&r)noexcept; (2)(since C++11) template<classY> weak_ptr(constweak_ptr<Y>&r)noexcept; (2)(since C++11) template<classY> weak_ptr(conststd::shared_ptr<Y>&r)noexcept; ...
#include <iostream> #include <memory> std::weak_ptr<int> gw; void f() { if (!gw.expired()) std::cout << "gw 有效\n"; else std::cout << "gw 已过期\n"; } int main() { { auto sp = std::make_shared<int>(42); gw = sp; f(); } f(); } 输出: gw 有效 gw 已...
std::swap(std::weak_ptr) Defined in header<memory> template<classT> voidswap(std::weak_ptr<T>&lhs,std::weak_ptr<T>&rhs)noexcept; (since C++11) Specializes thestd::swapalgorithm forstd::weak_ptr. Swaps the contents oflhsandrhs. Callslhs.swap(rhs). ...
cppreference.com中关于weak_ptr的使用情景中就有相关描述, 就和我遇到的情况一模一样: 如果你使用的一个对象可能随时会被删除,但是你无法控制何时被删除, 那么你就应该使用weak_ptr, 然后由对象的拥有者使用shared_ptr. 另外, weak_ptr对象在lock()之后会临时的生成一个shared_ptr, 在此期间对象将无法被其它人...
muduo就是再Channel中使用std::weak_ptr<void>。其有一个方法Channel::tie,接受const std::shared_ptr<void>&类型的参数,此参数要求传入持有socket描述符管理者对象的std::shared_ptr。muduo将此参数赋值给给std::weak_ptr<void>对象,使其可以监控socket描述符管理者对象是否已经析构。部分代码如下:...
weak_ptr - C++ Referencewww.cplusplus.com/reference/memory/weak_ptr/ 有: CMakeLists.txt cmake_minimum_required(VERSION 3.20) project ( testprj ) set ( PRJ_COMPILE_FEATURES ) list ( APPEND PRJ_COMPILE_FEATURES cxx_std_23 ) add_executable( ${PROJECT_NAME} main.cpp ) target_compile_fe...
根据cppreference,其中说 std::weak_ptr<T>::lock 有效返回expired() ? Shared_ptr() :shared_ptr(*this),原子执行。 这是示例代码。 #include<memory> #include<thread> std::shared_ptr<int> g_s = std::make_shared<int>(1); std::weak_ptr<int> w_p{g_s}; void f1(std::weak_ptr<int>...
然后std::shared_ptr<void>构造std::weak_ptr<void>就是理所当然的了。 那能不能由std::shared_ptr<T>直接构造std::weak_ptr<void>呢?按理来说是可以的,我们在cppreference里面找一下可以发现: // https://en.cppreference.com/w/cpp/memory/weak_ptr/weak_ptrtemplate<T>// 这两行是我自己加的,st...
#include <iostream> #include <memory> void observe(std::weak_ptr<int> weak) { if (auto observe = weak.lock()) { std::cout << "\tobserve() able to lock weak_ptr<>, value=" << *observe << "\n"; } else { std::cout << "\tobserve() unable to lock weak_ptr<>\n"; }...