std::weak_ptr::lock(3)
π NAME π
okay so bestie, welcome to the C++ Standard Libary page for std::weak_ptr::lock β and yes, the name is literally std::weak_ptr::lock, no cap π
β¨
β¨ Synopsis β¨
std::shared_ptr<T> lock() const noexcept; (since C++11)
It creates a new std::shared_ptr that shares ownership of the managed object π«Ά. If there is no managed object β like, if *this is empty β then the returned shared_ptr is also empty. Itβs giving βbestie checks if the vibe is still alive before handing you the keysβ π
Effectively it returns expired() ? shared_ptr<T>() : shared_ptr<T>(*this), and that whole thing is executed atomically β‘
π¦ Parameters π¦
(none) β not a single parameter, not even one little guy π
π Return value π
A shared_ptr which shares ownership of the owned object if std::weak_ptr::expired returns false. Else it returns a default-constructed shared_ptr of type T πΈ
π§ Notes π§
Both this function and the constructor of std::shared_ptr may be used to acquire temporary ownership of the managed object referred to by a std::weak_ptr π
The difference is that the constructor of std::shared_ptr throws an exception when its std::weak_ptr argument is empty, while std::weak_ptr<T>::lock() constructs an empty std::shared_ptr<T> β and that distinction is lowkey iconic, ngl π
π Example π
// Run this code
#include <iostream>
#include <memory>
void observe(std::weak_ptr<int> weak)
{
if (auto p = weak.lock())
std::cout << "\tobserve() is able to lock weak_ptr<>, value="
<< *p << '\n';
else
std::cout << "\tobserve() is unable to lock weak_ptr<>\n";
}
int main()
{
std::weak_ptr<int> weak;
std::cout << "weak_ptr<> is not yet initialized\n";
observe(weak);
{
auto shared = std::make_shared<int>(42);
weak = shared;
std::cout << "weak_ptr<> is initialized with shared_ptr\n";
observe(weak);
}
std::cout << "shared_ptr<> has been destructed due to scope
exit\n";
observe(weak);
}
πΈ Output πΈ
weak_ptr<> is not yet initialized
observe() is unable to lock weak_ptr<>
weak_ptr<> is initialized with shared_ptr
observe() is able to lock weak_ptr<>, value=42
shared_ptr<> has been destructed due to scope exit
observe() is unable to lock weak_ptr<>
π οΈ Defect reports π οΈ
The following behavior-changing defect reports were applied retroactively to previously published C++ standards π
- DR:
LWG 2316 - Applied to:
C++11 - Behavior as published:
lock()was not required to be atomic, but required to benoexcept, which led to a contradiction - Correct behavior: specified to be atomic
π See also π
expiredβ checks whether the referenced object was already deleted (public member function) π
mwah π β source/site: http://cppreference.com, version/date: 2024.06.10, page: std::weak_ptr::lock(3). periodt β¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms