Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vector 通过引用shared_ptr从函数中检索向量项_Vector_Stl_Containers_Shared Ptr_Unique Ptr - Fatal编程技术网

Vector 通过引用shared_ptr从函数中检索向量项

Vector 通过引用shared_ptr从函数中检索向量项,vector,stl,containers,shared-ptr,unique-ptr,Vector,Stl,Containers,Shared Ptr,Unique Ptr,我需要从函数中获取放置在唯一_ptr中的向量项并对其进行修改。修改应反映在原始容器中 数据严格使用锁进行维护,因此在我释放容器之前,没有其他线程可以修改它 下面的代码完成了这项工作,但在主函数的末尾崩溃了:表达式:_BLOCK_TYPE_IS VALID(pHead->nBlockUse) . 但是为什么呢? 独特的ptr也观察到相同的碰撞 有没有其他更好的抓取方法 #include <iostream> #include <vector> #include <me

我需要从函数中获取放置在唯一_ptr中的向量项并对其进行修改。修改应反映在原始容器中

数据严格使用锁进行维护,因此在我释放容器之前,没有其他线程可以修改它

下面的代码完成了这项工作,但在主函数的末尾崩溃了:表达式:_BLOCK_TYPE_IS VALID(pHead->nBlockUse) . 但是为什么呢? 独特的ptr也观察到相同的碰撞

有没有其他更好的抓取方法

#include <iostream>
#include <vector>
#include <memory>
using namespace std;

struct Item
{
    int i;
};
struct Data
{
    vector<Item> vec;
};
unique_ptr<Data> dataPtr(new Data());

void create()
{
    Item w;
    w.i = 2;
    dataPtr->vec.push_back(w);
    cout << "Data added\n";
}
void GetItem(shared_ptr<Item>& work)
{
    auto &w = dataPtr->vec.front();
    work.reset(&w);
}

int _tmain(int argc, _TCHAR* argv[])
{
    create();
    shared_ptr<Item> oldItem;
    GetItem(oldItem);
    oldItem->i = 3;
    cout << "Retrieved Item: " << oldItem->i << endl;
    cout << "Global Item: " << dataPtr->vec.front().i << endl;
    return 0;
}
#包括
#包括
#包括
使用名称空间std;
结构项
{
int i;
};
结构数据
{
向量向量机;
};
唯一的_ptr dataPtr(新数据());
void create()
{
项目w;
w、 i=2;
dataPtr->vec.推回(w);
cout vec.front();
工作。重置(&w);
}
int _tmain(int argc,_TCHAR*argv[]
{
创建();
共享项目;
GetItem(oldItem);
oldItem->i=3;

通过无问题地传递指针引用可以做到这一点。但是我想使用C++11特性而不是原始指针。
shared\u ptr
只能将指针包装到由
new
分配的对象。当
shard\u ptr
超出范围时,其析构函数将对底层原始指针调用
delete
,除非由
new
分配,否则将显示未定义的行为。有鉴于此,
工作。重置(&w)
是非法的,没有任何意义。为什么您再次觉得需要在此处使用
共享的ptr
?您没有实现共享所有权-所有项目显然都属于
dataPtr