GSP
Quick Navigator

Search Site

Unix VPS
A - Starter
B - Basic
C - Preferred
D - Commercial
MPS - Dedicated
Previous VPSs
* Sign Up! *

Support
Contact Us
Online Help
Handbooks
Domain Status
Man Pages

FAQ
Virtual Servers
Pricing
Billing
Technical

Network
Facilities
Connectivity
Topology Map

Miscellaneous
Server Agreement
Year 2038
Credits
 

USA Flag

 

 

Man Pages
std::weak_ptr::lock(3) C++ Standard Libary std::weak_ptr::lock(3)

std::weak_ptr::lock - std::weak_ptr::lock


std::shared_ptr<T> lock() const noexcept; (since C++11)


Creates a new std::shared_ptr that shares ownership of the managed object. If there
is no managed object, i.e. *this is empty, then the returned shared_ptr also is
empty.


Effectively returns expired() ? shared_ptr<T>() : shared_ptr<T>(*this), executed
atomically.


(none)


A shared_ptr which shares ownership of the owned object if std::weak_ptr::expired
returns false. Else returns default-constructed shared_ptr of type T.


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>.

// Run this code


#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";
}
}


int main()
{
std::weak_ptr<int> weak;
std::cout << "weak_ptr<> not yet initialized\n";
observe(weak);


{
auto shared = std::make_shared<int>(42);
weak = shared;
std::cout << "weak_ptr<> initialized with shared_ptr.\n";
observe(weak);
}


std::cout << "shared_ptr<> has been destructed due to scope exit.\n";
observe(weak);
}


weak_ptr<> not yet initialized
observe() unable to lock weak_ptr<>
weak_ptr<> initialized with shared_ptr.
observe() able to lock weak_ptr<>, value=42
shared_ptr<> has been destructed due to scope exit.
observe() unable to lock weak_ptr<>


Defect reports


The following behavior-changing defect reports were applied retroactively to
previously published C++ standards.


DR Applied to Behavior as published Correct behavior
lock() was not required to be atomic, but
LWG 2316 C++11 required to be noexcept, which led to a specified to be atomic
contradiction


expired checks whether the referenced object was already deleted
(public member function)

2022.07.31 http://cppreference.com

Search for    or go to Top of page |  Section 3 |  Main Index

Powered by GSP Visit the GSP FreeBSD Man Page Interface.
Output converted with ManDoc.