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)
.
它是可行的代码。 C ++规范?
即使标准涵盖了它,但它当然不是很好的样式,并且 如果代码更改,则容易出错,例如如果方法是 重构为虚拟方法。我只是好奇什么 标准必须说,无论是g ++代码字是通过设计还是仅通过 事故。
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);
}
输出量
1
2
Assertion failed: this, file main.cpp, line 16