Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weak_ptr reset affects shared_ptr?

I'm not very used to using weak_ptr and I'm facing a quite confusing situation. I'm using Intel XE 2019 Composer update 5 (package 2019.5.281) in combinaison with Visual Studio 2019 ver. 16.2.5. I compile in 64-bit. I use the standard C++ 17.

Here is the code for my spike solution:

#include <memory>
#include <iostream>

using namespace std;

int main( int argc, char* argv[] )
{
    shared_ptr<int> sp = make_shared<int>( 42 );
    cout << "*sp = " << *sp << endl;

    weak_ptr<int> wp = sp;
    cout << "*sp = " << *sp << ", *wp = " << *wp.lock() << endl;

    wp.reset();
    cout << "*sp = " << *sp << endl;

    return 0;
}

The output I expected to have is:

*sp = 42
*sp = 42, *wp = 42
*sp = 42

...but here is what I obtained:

*sp = 42
*sp = 42, *wp = 42
*sp = -572662307

What is goin on? Is it normal for the shared_ptr to be modified/invalidated when the/an associated weak_ptr is reset? I'm a little confused about the results I obtained. To say the truth I didn't expect this result...

EDIT 1

While the bug occurs in 64-bit configuration, it doesn't in 32-bit. In this later configuration, the result is what is expected.

EDIT 2

The bug occurs only in Debug. When I build in Release, I get the expected result.

like image 600
dom_beau Avatar asked Oct 04 '19 13:10

dom_beau


People also ask

What is the difference between shared_ptr and weak_ptr?

The only difference between weak_ptr and shared_ptr is that the weak_ptr allows the reference counter object to be kept after the actual object was freed. As a result, if you keep a lot of shared_ptr in a std::set the actual objects will occupy a lot of memory if they are big enough.

What does weak_ptr lock do?

weak_ptr::lockCreates 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.

How can a weak_ptr be turned into a shared_ptr?

The weak_ptr class template stores a "weak reference" to an object that's already managed by a shared_ptr. To access the object, a weak_ptr can be converted to a shared_ptr using the shared_ptr constructor or the member function lock.

Is weak_ptr lock thread safe?

Using weak_ptr and shared_ptr across threads is safe; the weak_ptr/shared_ptr objects themselves aren't thread-safe. You can't read/write to a single smart pointer across threads.


1 Answers

It appears it is a real bug on Intel ICC side; I have reported it.

Thanks again for helping me to pin-point this problem.

like image 54
dom_beau Avatar answered Oct 21 '22 10:10

dom_beau