#include <cstdio>
class A
{
public:
A(int){puts("3");};
int foo(){puts("4");return 10;}
};
int main()
{
A a(a.foo());
return 0;
}
Outputs 4 and 3.
It calls a member function before calling the constructor. Is the behavior defined by the standard?
the constructor is the first function which get called. and we can access the this pointer via constructor for the first time. if we are able to get the this pointer before constructor call (may be via malloc which will not call constructor at all), we can call member function even before constructor call.
So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended.
C and C++ have undefined behaviors because it allows compilers to avoid lots of checks. Suppose a set of code with greater performing array need not keep a look at the bounds, which avoid the needs for complex optimization pass to check such conditions outside loops.
§12.7 [class.cdtor]/p1:
For an object with a non-trivial constructor, referring to any non-static member or base class of the object before the constructor begins execution results in undefined behavior.
A conforming compiler is allowed to emit code that blows your legs off.
Yes. In practice, it may work, because A::foo
doesn't se any state from a
instance. You should never write code like this (and you should probably correct it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With