Windows apps
Collapse the table of content
Expand the table of content
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.
We recommend using Visual Studio 2017

weak_ptr::lock

Obtains exclusive ownership of a resource.

shared_ptr<Ty> lock() const;

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.

 

// 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::tr1::weak_ptr<int> wp; 
 
     { 
    std::tr1::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

Header: <memory>

Namespace: std::tr1

Community Additions

Show:
© 2018 Microsoft