samedi 9 mai 2020

C++: Is "assert (this)" a viable pattern?

Suppose the C++ below. Before calling of a->method1() it has an assert (a) to check if a is sane.

The call a->method2() has no such assertion; instead method2 itself checks for a valid this by means of assert (this).

It that viable code re. the C++ specification?

Even if it's covered by the standard, it not good style of course, and it's error prone if the code ever changes, e.g. if the method is refactored to a virtual method. I am just curios about what the standard has to say, and whether g++ code words by design or just by accident.

The code below works as expected with g++, i.e. the assertion in method2 triggers as intended, because just to call method2 no this pointer is needed.

#include <iostream>
#include <cassert>

struct A
{
    int a;
    A (int a) : a(a) {}

    void method1 ()
    {
        std::cout << a << std::endl;
    }

    void method2 ()
    {
        assert (this);
        std::cout << a << std::endl;
    }
};

void func1 (A *a)
{
    assert (a);
    a->method1();
}

void func2 (A *a)
{
    a->method2();
}

int main ()
{
    func1 (new A (1));
    func2 (new A (2));
    func2 (nullptr);
}

Output

1
2
Assertion failed: this, file main.cpp, line 16

Aucun commentaire:

Enregistrer un commentaire