Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.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
C++ 获取“共享”的ptr;这";对象指向另一个函数:给定运行时异常_C++_Shared Ptr_Smart Pointers - Fatal编程技术网

C++ 获取“共享”的ptr;这";对象指向另一个函数:给定运行时异常

C++ 获取“共享”的ptr;这";对象指向另一个函数:给定运行时异常,c++,shared-ptr,smart-pointers,C++,Shared Ptr,Smart Pointers,实际上,我想从另一个函数中的“this”对象中提取共享的_ptr。 对于相同的情况,假设我们有一个“Thing member function”需要将指向“this”对象的指针传递给另一个函数,如: #include "stdafx.h" #include<memory> using namespace std; class Thing { public: void foo(); void defrangulate(); }; void Thing::defrangula

实际上,我想从另一个函数中的“this”对象中提取共享的_ptr。 对于相同的情况,假设我们有一个“Thing member function”需要将指向“this”对象的指针传递给另一个函数,如:

#include "stdafx.h"

#include<memory>

using namespace std;


class Thing {
public:
 void foo();
 void defrangulate();
};
void Thing::defrangulate()
{
}

void transformIt(shared_ptr<Thing> ptr)
{
 ptr->defrangulate();
 /* etc. */
}

void Thing::foo()
{
 // we need to transformIt this object
 shared_ptr<Thing> sp_for_this(this);
 transformIt(sp_for_this);
}

int main()
{
 shared_ptr<Thing> t1(new Thing);// start a manager object for the Thing
 t1->foo();
}
#包括“stdafx.h”
#包括
使用名称空间std;
阶级事务{
公众:
void foo();
void defrangulate();
};
void Thing::defrangulate()
{
}
无效转换(共享)
{
ptr->defrangulate();
/*等等*/
}
void Thing::foo()
{
//我们需要把它转换成这个物体
此(本)的共享\u ptr sp\u;
转换(sp_用于此);
}
int main()
{
共享的_ptr t1(新事物);//为该事物启动一个管理器对象
t1->foo();
}
输出: 调试断言失败! 表达式:\块\类型\有效(pHead->nBlockUse)


我是否犯了导致此运行时异常的任何错误

您正在导致双重删除。这是因为当您从中创建一个共享\u ptr时,您不会告诉它原始指针已经被其他人拥有。您需要使用自定义的无操作删除器(使用
(this,[](void*){})构造共享的\u ptr)或使用。

您导致了双重删除。这是因为当您从中创建共享的\u ptr时,您不会告诉它原始指针已经被其他人拥有。您需要使用自定义的无操作删除器(与
(this,[](void*){}构造共享的\u ptr)
,或使用。

那个错误消息对我来说意味着内存损坏。我看不出你的代码有任何明显的错误,我建议
valgrind
。这就是为什么我更喜欢对函数参数使用原始指针而不是共享指针。那个错误消息对我来说意味着内存损坏。我看不到你有任何明显的错误r代码,建议使用
valgrind
。这就是为什么对于函数参数,我更喜欢使用原始指针而不是共享指针。