如何在智能指针中正确使用this指针?shared_ptr使用异常求助
问题根源与解决方法
你的核心问题是直接用this构造新的std::shared_ptr,这会生成一个独立的引用计数实例。当这个临时shared_ptr销毁时,会误以为对象没有其他所有者,直接触发析构,导致对象被意外销毁。
正确使用shared_from_this的步骤
要安全获取当前对象的shared_ptr,必须让RectCollider继承std::enable_shared_from_this,且遵循以下规则:
1. 修改类定义
确保RectColliderpublic继承std::enable_shared_from_this<RectCollider>,模板参数必须是当前类类型:
class RectCollider : public Collider, public std::enable_shared_from_this<RectCollider> { // 类成员与方法定义 };
2. 修正成员函数中的指针获取逻辑
在CheckCollision中,用shared_from_this()替代直接用this构造shared_ptr:
bool RectCollider::CheckCollision(std::shared_ptr<Collider> other, Vector3& normal, float& depth) { auto thisPtr = shared_from_this(); // 获取当前对象的shared_ptr std::shared_ptr<RectCollider> otherRect = std::dynamic_pointer_cast<RectCollider>(other); if (otherRect) { if (otherRect == thisPtr) return false; return Collision::RectCollision(thisPtr, otherRect, normal, depth); } std::shared_ptr<CircleCollider> otherCircle = std::dynamic_pointer_cast<CircleCollider>(other); if (otherCircle) { return Collision::CircleRectCollision(thisPtr, otherCircle, normal, depth); } return false; }
排查shared_from_this之前失效的可能原因
如果之前用shared_from_this没生效,大概率是以下情况之一:
- 类没有继承
std::enable_shared_from_this,或者继承的模板参数错误(比如写成enable_shared_from_this<Collider>) - 当前对象不是由
std::shared_ptr管理的(比如栈上创建的对象,或者用new直接分配后未交给shared_ptr) - 在对象的构造函数中调用了
shared_from_this(此时还没有shared_ptr接管对象,会触发未定义行为)
内容的提问来源于stack exchange,提问作者Илина Бокарева
相关产品推荐
相关产品推荐

