从Debug Assertion Failed: _CrtIsValidHeapPointer(block)看shared_ptr

在实现渲染器的BVH树时,遇到Debug Assertion Failed: _CrtIsValidHeapPointer(block)错误。问题源于将 Plane 实例的 this 指针转为 shared_ptr 并传给 BoundingBox,由于 Plane 是通过 std::make_shared 创建,导致析构时引用计数减少并误删,引发双删错误。解决方案是正确管理智能指针。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近给自己的渲染器实现一下BVH树来进行求交加速的时候,设计了一个数据结构BoundingBox。

BoundingBox之间层级嵌套,位于叶子的box保存了对应的图元最小单位(比如三角形)。这里实现的方法是每种图元实现一个GenBox的虚函数,在GenBox时把自身作为参数传进去。比如Plane的对应函数如下:

std::shared_ptr<BoundingBox> Plane::GenBox() const {
	double xMin, xMax, yMin, yMax, zMin, zMax;
	xMin = std::min(std::min(p1.x, p2.x), std::min(p3.x, p4.x));
	xMax = std::max(std::max(p1.x, p2.x), std::max(p3.x, p4.x));
	yMin = std::min(std::min(p1.y, p2.y), std::min(p3.y, p4.y));
	yMax = std::max(std::max(p1.y, p2.y), std::max(p3.y, p4.y));
	zMin = std::min(std::min(p1.z, p2.z), std::min(p3.z, p4.z));
	zMax = std::max(std::max(p1.z, p2.z), std::max(p3.z, p4.z));

	auto box = std::make_shared<BoundingBox>(xMin, xMax, yMin, yMax, zMin, zMax);
	box->AddGeo(std::shared_ptr<Geometry>(this));

	return box;
}

然而在运行时一直出现Debug Assertion Failed: _CrtIsValidHeapPointer(block)这个错误。通过查询相关资料后发现是指针被delete两次导致。于是最后定位到了这一语句:


                
void QtWidgets1::pushButton2_C() { if (!cloudrgb || cloudrgb->empty()) { qWarning() << "点云数据为空!"; return; } try { // 使用自动推导和make_shared优化创建方式 auto seg = std::make_shared<pcl::SACSegmentation<pcl::PointXYZRGB>>(); auto inliers = std::make_shared<pcl::PointIndices>(); auto coefficients = std::make_shared<pcl::ModelCoefficients>(); // 保持原有参数设置... // 使用reset避免重复分配内存 auto cloud_plane = std::make_shared<pcl::PointCloud<pcl::PointXYZRGB>>(); auto cloud_remaining = std::make_shared<pcl::PointCloud<pcl::PointXYZRGB>>(); pcl::ExtractIndices<pcl::PointXYZRGB> extract; extract.setInputCloud(cloudrgb); // 平面提取 extract.setIndices(inliers); extract.setNegative(false); extract.filter(*cloud_plane); // 剩余点云提取 extract.setNegative(true); extract.filter(*cloud_remaining); // 显式传递所有权 //emit updateCloudDisplay(std::move(cloud_plane), CloudType::PLANE); //emit updateCloudDisplay(std::move(cloud_remaining), CloudType::REMAINING); qDebug() << "平面方程系数:" << coefficients->values; } catch (const std::exception& e) { qCritical() << "分割错误:" << e.what(); // 智能指针会自动释放资源 } }报错Debug Assertion Failed! Program:D:\SLH\C\BaiduSyncdisk QtWidgets1\x64\Debug\QtWidgets1.exe File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp Line: 904Expression:_CrtlsValidHeapPointer(block)For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts. (Press Retry to debug the application)
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值