简体   繁体   中英

Passing a ptr to a ptr to A as parameter to a function of A is bad practice?

Is passing a pointer to a pointer to object A as a parameter of a function in A bad practice?

Here's an example:

class A
{
    A** ptrToMyself;

    void Foo(A*& refToPtrToMyself)
    {
        ptrToMyself = &refToPtrToMyself;
    }
}
class B
{
    A* ptrToA;
    void Bar()
    {
        ptrToA = new A();
        ptrToA->Foo(ptrToA);
    }
}

The reason I need this is that B will create an instance of A, then A will run and will destroy itself later. Since I don't want to have an invalid pointer in BI set that pointer to nullptr.

EDIT:

So, as some have asked I'm going to clarify what I'm going to be using this for. I'm making a game in UE4 and, basically, class A represents the Attack class I have (I inherit it and override some virtual functions to add functionality) and B represents my character class. When the player presses the attack button I instantiate the class of the attack the player has selected. Then the attack executes, plays animations and does all it has to do. When it finishes it just destroys itself (and clears the reference the character had to it).

Passing a pointer to the instance doesn't make sense at all—that's already what the this pointer is.

The bigger problem here is that you haven't thought enough about the determinants of the lifetime of your objects and more generally about the underlying asynchronicity and the conflicts it might raise etc.

Asynchronous animations basically mean that your animation classes need to hold shared pointers to all objects they will need (attacks etc.). That's precisely why shared pointers exist; you can initialize a shared pointer in some member function of B, make a copy of it in some non-blocking animation function, then it doesn't matter if you get rid of the shared pointer that B holds, the object will exist as long as some animation object holds on a pointer to it. And if your b keeps a weak_ptr to the shared_ptr of a that exist elsewhere, the b can keep track of whether a has been destroyed.

Anyway, the main question is where do you keep track of ongoing animations?

You don't need the attack to delete itself. Just use a smart pointer (std or UE4) and let it delete itself:

#include <memory>
#include <iostream>

class AttackInterface
{
public:
    virtual void foo() = 0;
};

class Attack: public AttackInterface
{
public:
    void foo() { std::cout << "deal damage" << std::endl;}
};

class Character
{
public:
    void behave()
    {
        std::shared_ptr<Attack> attack = std::make_shared<Attack>();
        attack->foo();
    }
};

int main()
{
    Character c;
    c.behave();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM