Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++ shared pointer not behave like standard pointer for iterators?

I'm about to make a random number generator in C++ and in order to avoid copying too big vectors, I wanted to pass pointers to them. I don't want to take care of garbage collection myself. That's why I want to use shared_ptr (I may add that I'm a newby, so maybe my approach is clumsy/not fitted for the problem.). Now I want to search the vector but there is a strange behavior of shared_ptr and shared_ptr.get(), respectively: Either they do not find the right solution (see code snippet) or they even throw a

First-chance exception at 0x0131F5DA in MonteCarlo.exe: 0xC0000005: Access violation reading location 0x00000008.

in other cases. I see that the location is close to 0 (= null-pointer), but why?

Using standard pointers yields correct results. Here my code snippet:

    #include <typeinfo>
#include <algorithm> 
#include <vector>
#include <memory>
using namespace std;

int j = 3;    
vector< int > v;  
v.push_back(1);  
v.push_back(3);  
v.push_back(5);
vector< int >* v_pointer = &v;
shared_ptr<vector< int >> v_shared = make_shared<vector<int>>();
vector< int >* v_pointer_from_shared = v_shared.get();

// printing types of objects
cout << typeid(v.begin()).name() << endl;
cout <<  typeid(v_pointer->begin()).name() << endl; 
cout << typeid(v_shared->begin()).name() << endl;

// do search
if (binary_search(v.begin(), v.end(), j)) cout << "yeah" << endl;
if (binary_search(v_pointer->begin(), v_pointer->end(), j)) cout << "yeah2" << endl;
if (binary_search(v_shared->begin(), v_shared->end(), j)) cout << "yeah3" << endl;
if (binary_search(v_pointer_from_shared->begin(), v_pointer_from_shared->end(), j)) cout << "yeah4" << endl;

Output:

yeah

yeah2

So why doesn't yeah3 show up? For the typeid is the same... or at least yeah4, which is again a normal pointer. I guess, there is some theory about shared_pointers which I don't understand...

I use VS 2012 Express on 64bit Windows 7.

like image 332
Andarin Avatar asked Oct 21 '22 08:10

Andarin


1 Answers

Look at how you set up the shared_ptr and normal vector:

int j = 3;    
vector< int > v;  
v.push_back(1);  
v.push_back(3);  
v.push_back(5);
vector< int >* v_pointer = &v;
shared_ptr<vector< int >> v_shared = make_shared<vector<int>>();
vector< int >* v_pointer_from_shared = v_shared.get();

You've never inserted anything into the vector pointed at by your shared_ptr, so the correct behavior here when doing the binary_search would be to report that no values are present in the vector. Note that v and the vector you're pointing at aren't the same vector, nor should they be.

Hope this helps!

like image 69
templatetypedef Avatar answered Oct 24 '22 04:10

templatetypedef