C ++:“断言(此)”是可行的模式吗?

问题描述 投票:0回答:2

假设下面的C ++。在调用a->method1()之前,它具有一个assert (a)检查a是否健全。

呼叫a->method2()没有这样的断言;代替method2本身通过this检查有效的assert (this)

这是可行的代码。 C ++规范?

即使被标准覆盖,它当然也不是好的样式,并且如果代码更改,则容易出错,例如如果方法是重构为虚拟方法。我只是好奇什么标准必须说,无论是g ++代码字是通过设计还是仅通过事故。

下面的代码可以在g ++中正常工作,即method2会按预期触发,因为仅调用method2否需要this指针。

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

输出

1
2
Assertion failed: this, file main.cpp, line 16
c++ design-patterns assertion null-pointer this-pointer
2个回答
0
投票

[this不能为nullptr,(否则已经存在未定义的行为)。

根据您的情况

a->method2(); // with a == nullptr

调用未定义的行为,因此事后检查是没有用的。

更好的签名意味着不是空指针是引用:

void func3(A& a)
{
    a.method1();
}

int main ()
{
    A a1(1); // no new, so no (missing) delete :-)
    A a2(2);

    func1(&a1);
    func2(&a2);
    func2(nullptr); :/
    func3(a1);
}

0
投票

assert(this);无意义。 C ++标准保证在有效程序中this指针为never nullptr

如果您的程序有undefined behaviour,那么所有下注当然都是关闭的,this可能是nullptr。但是在这种情况下,断言不是正确的解决方案,而修复UB是正确的。

© www.soinside.com 2019 - 2024. All rights reserved.