2

from this question (still not solved) I come across this new problem,so here I made an example:

//main.cpp  

int main() {
    return 0;
}

//file1.cpp
#include "b.h"
B b;

//file2.cpp
#include "a.h"
A a;

//a.h
#pragma once
#include<iostream>
#include "b.h"
extern B b;
class A
{
public:
    A(){ std::cout << "a cotr" << std::endl;b.Use(); }
};

//b.h
#pragma once
#include<iostream>
class B
{
public:
    B() { std::cout << "b ctor"<<std::endl; };
    void Use() { std::cout << "use b" << std::endl; }
};

In g++ 6.3.0 the output is:( g++ -o test file1.cpp file2.cpp prac.cpp -std=c++11)
a cotr
use b
b ctor

So from the code example it seems that there's no such guarantee,and probably is an undefined behavior ?Is there anywhere the standard said about this?(I do not think it's a duplicate because this situation is a little different:in the initialization of a,invoke b's member function.)

choxsword
  • 3,187
  • 18
  • 44

1 Answers1

1

Is object guaranteed to be initialized before calling its member function?

No, it is your job not to call any non-static member function on invalid object, that includes but not limited to passing nullptr as this, object not created yet or already destroyed object. One of the solution of this situation is to have static local object in a function instead of global one and return reference/pointer to it. That method still have problem with destruction order, but at least half of the problem is gone.

Slava
  • 43,454
  • 1
  • 47
  • 90
  • So you mean that calling non-static member function of `obj.foo()` before `obj` is construted is undefined behavior?What about static member fuction? – choxsword Apr 13 '18 at 13:39
  • Static member functions are fine (they are basically no different to a global function) as long as they don't access any static member variables which aren't yet initialised. – Alan Birtles Apr 13 '18 at 13:42