Search code examples
c++thissmart-pointersweak-ptr

How to use 'this' pointer with smart pointers


I have a static function where I pass a collider and the other collider is itself. I used a regular pointer before and changed it to shared_ptr. I can't find a solution to how I can pass this as a shared pointer. Everytime I do something it seems it deletes itself inside the function.

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;
}

I'm sure thisGo is the problem.

I trid to use ChatGPT and it gave me this code and shared_from_this but it doesn't work.


Solution

  • thank you for helping, I figured out what's wrong myself this how I fixed the script

    bool RectCollider::CheckCollision(std::shared_ptr<Collider> other, Vector3& normal, float& depth) {
        
        std::shared_ptr<RectCollider> otherRect = std::dynamic_pointer_cast<RectCollider>(other);
        std::shared_ptr<Collider> sharedThis = shared_from_this();
        if (otherRect) {
            
            if (otherRect == sharedThis) 
                return false;
            return Collision::RectCollision(sharedThis, otherRect, normal, depth);
        }
    
        std::shared_ptr<CircleCollider> otherCircle = std::dynamic_pointer_cast<CircleCollider>(other);
        if (otherCircle) {
            return Collision::CircleRectCollision(sharedThis, otherCircle, normal, depth);
        }
    
        return false;
    }