为什么C++共享指针的行为不像迭代器的标准指针?

And*_*rin 5 c++ pointers vector binary-search shared-ptr

我要用C++制作一个随机数生成器,为了避免复制太大的向量,我想把指针传递给它们.我不想自己处理垃圾收集.这就是为什么我想使用shared_ptr(我可能会补充说我是一个新手,所以也许我的方法是笨拙的/不适合这个问题.).现在我想搜索向量,但分别有一个奇怪的行为:shared_ptr和shared_ptr.get():要么找不到合适的解决方案(参见代码片段),要么他们甚至抛出一个

MonteCarlo.exe中0x0131F5DA的第一次机会异常:0xC0000005:访问冲突读取位置0x00000008.

在其他情况下.我看到该位置接近于0(=空指针),但为什么呢?

使用标准指针可以得到正确的结果.这是我的代码片段:

    #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;
Run Code Online (Sandbox Code Playgroud)

输出:

是啊

yeah2

那么,为什么不yeah3显示出来?因为typeid是相同的...或者至少是yeah4,这也是一个普通的指针.我想,有一些关于shared_pointers的理论,我不明白......

我在64位Windows 7上使用VS 2012 Express.

tem*_*def 3

看看你如何设置shared_ptr和 正常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();
Run Code Online (Sandbox Code Playgroud)

您从未将任何内容插入到vector您的 指向的位置shared_ptr,因此执行此操作时,正确的行为binary_search是报告 中不存在任何值vector。请注意,您指向的vvector并不相同vector,也不应该相同。

希望这可以帮助!