我有一个静态函数,我传递一个碰撞器,另一个碰撞器是它本身。我之前使用的是常规指针,并将其更改为shared_ptr。我找不到如何将其作为共享指针传递的解决方案。每次我做某事时,它似乎都会在函数内删除自身。
bool RectCollider::CheckCollision(std::shared_ptr<Collider> other, Vector3& normal, float& depth) {
std::shared_ptr<RectCollider> otherRect = std::dynamic_pointer_cast<RectCollider>(other);
std::weak_ptr<RectCollider> thisGo = std::shared_ptr<RectCollider>(this);
if (otherRect) {
if (otherRect == thisGo.lock())
return false;
return Collision::RectCollision(thisGo.lock(), otherRect, normal, depth);
}
std::shared_ptr<CircleCollider> otherCircle = std::dynamic_pointer_cast<CircleCollider>(other);
if (otherCircle) {
return Collision::CircleRectCollision(thisGo.lock(), otherCircle, normal, depth);
}
return false;
}
我确定这就是问题所在。谢谢
我尝试使用chatGBT,它给了我这个代码和shared_from_this,但它不起作用
std::shared_ptr
有一个引用计数器,也就是说,它跟踪有多少个std::shared_ptr
实例指向同一个对象。每次 std::shared_ptr
超出范围时,计数器就会递减。如果达到 0,则指向的对象将被释放。
让我们看一个简单的例子:
#include <memory>
class Obj {
public:
Obj() {
std::shared_ptr<Obj>(this);
}
};
int main() {
Obj o;
return 0;
}
构建
Obj
时,我们创建一个临时的 std::shared_ptr<Obj>
。它将被创建,引用计数器变为 1,然后(因为它是临时的)它会再次被销毁,并且引用计数器将递减为 0。这意味着临时对象将尝试通过 delete
指针来访问我们的对象 this
。但是 this
不是通过 new
分配的,并且 delete
不是通过 new
获取的内存是 UB (未定义行为)。