Namespaces
Variants
Views
Actions

std::weak_ptr::lock

From cppreference.com
< cpp‎ | memory‎ | weak ptr
Revision as of 15:43, 5 April 2013 by Jbenshetler (Talk | contribs)

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

Creates a new 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).

Contents

Parameters

(none)

Return value

A shared_ptr which shares ownership of the owned object.

Exceptions

noexcept specification:  
noexcept
  

Notes

Both this function and the constructor of shared_ptr may be used to acquire temporary ownership of the managed object. The difference is that the constructor of std::shared_ptr<T> throws an exception when the std::weak_ptr argument is empty, while std::weak_ptr<T>::lock() constructs an empty std::shared_ptr<T>.

Example

#include <iostream>
#include <memory>
#include <thread>
 
typedef std::shared_ptr<int> IntPtr;
typedef std::weak_ptr<int> IntWeakPtr;
 
 
 
void observe(IntWeakPtr pWeak) 
{
    IntPtr pObserve( pWeak.lock() );
    if ( pObserve ) 
    {
        std::cout << "\tobserve() able to lock weak_ptr<>, value=" << *pObserve << "\n";
    } else {
        std::cout << "\tobserve() unable to lock weak_ptr<>\n";
    }
}
 
int main(int argc, char* argv[])
{
    IntWeakPtr pWeak;
    std::cout << "weak_ptr<> not yet initialized\n";
    observe(pWeak);
    {
        IntPtr pShared( new int(42) );
        pWeak = pShared;
        std::cout << "weak_ptr<> initialized with shared_ptr.\n";
        observe(pWeak);
    }
    std::cout << "shared_ptr<> has been destructed due to scope exit.\n";
    observe(pWeak);
 
    return 0;
}

Output:

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

See also

Template:cpp/memory/weak ptr/dcl list expired