Why am I getting an access violation when locking weak_ptr?

I have std :: weak_ptr. Before trying to use the base object, I lock it to get shared_ptr:

auto foo_sharedptr = foo_weakptr.lock();
if (foo_sharedptr != nullptr)
{
    // do stuff with foo
}

This usually works fine. However, sometimes I get an access violation during a call to block:

Unhandled exception at 0x00007FF91F411BC3 (My.dll) in My.exe:  
0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.

I assume the main pointer has been removed, but my understanding of weak_ptr is that in this case, the lock should return nullptr. Am I abusing the type? If not, how do I go about debugging?

+4
source share
1 answer

EDIT: Despite this, this does not seem to be the correct answer, sorry:

http://en.cppreference.com/w/cpp/memory/shared_ptr/operator_cmp

template< class T >
bool operator==( const shared_ptr<T>& lhs, std::nullptr_t rhs );
    (7)     (since C++11)
template< class T >
bool operator!=( const shared_ptr<T>& lhs, std::nullptr_t rhs );
    (9)     (since C++11)

7)! lhs
9) (bool) lhs

.... ?? .


gcc -std = ++ 11: ( http://en.cppreference.com/w/cpp/memory/weak_ptr )

#include <iostream>
#include <memory>

std::weak_ptr<int> gw;

void f()
{
    auto spt = gw.lock();
    if (spt != nullptr) {
        std::cout << *spt << "\n";
    }
    else {
        std::cout << "gw is expired\n";
    }
}

int main()
{
    {
        auto sp = std::make_shared<int>(42);
        gw = sp;
        f();
    }

    f();
}

:

42
gw is expired


:

: bool, nullptr ( lhs.get() == rhs.get(), rhs = shared_ptr nullptr):

auto foo_sharedptr = foo_weakptr.lock();
if (foo_sharedptr)
{
    // do stuff with foo
}

. :

#include <iostream>
#include <memory>
#include <thread>

void observe(std::weak_ptr<int> weak) 
{
    std::shared_ptr<int> observe(weak.lock());
    if (observe) {
        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);

    {
        std::shared_ptr<int> shared(new 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);
}
+1

All Articles