[英]Getting shared_ptr for “this” object to another function : giving run time exception
实际上,我想从另一个函数中的“ 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 (this, [](void*){})
,或使用std::enable_shared_from_this
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.