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...
While the bug occurs in 64-bit configuration, it doesn't in 32-bit. In this later configuration, the result is what is expected.
The bug occurs only in Debug. When I build in Release, I get the expected result.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With