获取"this"对象到另一个函数的shared_ptr:给出运行时异常
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),或者使用std::enable_shared_from_this
。
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 我在c++代码中生成了一个运行时#3异常
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- c++中的指针和运行时错误
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 建议在运行时将带有类实例的列表从c++导入qml
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 如何在GTK程序运行时禁用屏幕保护程序/电源管理/屏幕消隐
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 读取文件时运行时的未知行为
- 函数在Windows或Linux上运行时表现不同
- 在声明中合并两个常量"std::set"(不是在运行时)
- AWS Lambda C++运行时权限被拒绝
- 通过switch和static_cast访问多态对象的运行时类型
- Linux中的c++运行时错误::glibc检测到free():无效的下一个大小(快速):堆栈具有void ptr元素