获取"this"对象到另一个函数的shared_ptr:给出运行时异常

Getting shared_ptr for "this" object to another function : giving run time exception

本文关键字:ptr 运行时 异常 对象 this 另一个 获取 函数 shared      更新时间:2023-10-16

实际上我想在另一个函数中从'this'对象中提取shared_ptr。同样,假设有一种情况,"Thing成员函数"需要将指向"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();
}

输出:调试断言失败!表情:_BLOCK_TYPE_IS_VALID (pHead -> nBlockUse)

我做任何错误导致这个运行时异常?

您正在引起双重删除。这是因为当您由此创建shared_ptr时,您不会告诉它原始指针已经由其他人拥有。您需要使用自定义的无操作删除器(用(this, [](void*){})构造shared_ptr),或者使用std::enable_shared_from_this