hczstev
hczstev

Reputation: 73

Is validating *this* ptr in member function a good practice?

Suppose I have a class

class Foo {
public:
    void fn();
private:
    int i;
};

and a find function

Foo* findFoo() {
    // return nullptr if failed to find
}

we may check if we did find Foo before calling member

{
    Foo* foo = findFoo();
    if (foo) {
        foo->fn();
    }
}

I think this "if" statement is redundant. if we can provide a default behavior for nullptr case, it would be more direct. So I figure out a practice:


void Foo::fn() {
    if (this == nullptr) { return; } // default behavior is to return for nullptr
    i; // access to member
}

we can use it directly without check nullptr

{
    findFoo()->fn();
}

compare "this" to "nullptr" is sure not a normal use of this, so I wonder if it has some side effect or drawbacks


"redundent" may lead to misunderstanding. I actually mean "noisy" here. Suppose Foo optionally contains a class Foo_1, Foo1 optionally contains a class Foo_2, ... Foo_n.

If I want to call a member function of Foo_n from a Foo if Foo_n is contained recursively in Foo, I should check every level of Foo_x with a if statement. I think it's noisy. If check this in member function, it can be called like foo->get_foo_1()->get_foo_2()->...->get_foo_n()->call()

Upvotes: 0

Views: 142

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123114

I think this "if" statement is redundant

It is not. You cannot check if this is nullptr inside a member function because if it was you cannot call a member function to begin with.

Foo* foo = findFoo();
if (foo) {
    foo->fn();
}

When findFoo returns nullptr then calling foo->fn() directly without the check would invoke undefined behavior. You can think of foo->fn() as (*foo).fn() and dereferencing a null pointer makes no sense, more formally: it is undefined.

The check in the above code is not redundant. The check inside the member function is. Because you can only be inside a member function when this is not nullptr.

Upvotes: 5

Related Questions