Share via


weak_ptr::lock

Obtains exclusive ownership of a resource.

shared_ptr<Ty> lock() const;

Remarks

The member function returns an empty shared_ptr object if *this has expired; otherwise it returns a shared_ptr Class<Ty> object that owns the resource that *this points to.

Example

 

// std_tr1__memory__weak_ptr_lock.cpp 
// compile with: /EHsc 
#include <memory> 
#include <iostream> 
 
struct deleter 
    { 
    void operator()(int *p) 
        { 
        delete p; 
        } 
    }; 
 
int main() 
    { 
    std::weak_ptr<int> wp; 
 
     { 
    std::shared_ptr<int> sp(new int(10)); 
    wp = sp; 
    std::cout << "wp.expired() == " << std::boolalpha 
        << wp.expired() << std::endl; 
    std::cout << "*wp.lock() == " << *wp.lock() << std::endl; 
     } 
 
// check expired after sp is destroyed 
    std::cout << "wp.expired() == " << std::boolalpha 
        << wp.expired() << std::endl; 
    std::cout << "(bool)wp.lock() == " << std::boolalpha 
        << (bool)wp.lock() << std::endl; 
 
    return (0); 
    } 
 
wp.expired() == false
*wp.lock() == 10
wp.expired() == true
(bool)wp.lock() == false

Requirements

Header: <memory>

Namespace: std

See Also

Reference

weak_ptr Class

Other Resources

<memory> Members