Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using a member function as an argument to a constructor undefined behavior?

#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?

like image 435
AntiMoron Avatar asked Sep 01 '14 07:09

AntiMoron


People also ask

Can we call member function using this pointer from constructor?

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.

What is undefined behavior in C++?

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.

Why does C allow undefined behavior?

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.


2 Answers

§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.

like image 82
T.C. Avatar answered Oct 02 '22 18:10

T.C.


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).

like image 45
utnapistim Avatar answered Oct 02 '22 20:10

utnapistim