问题
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.)
回答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.
来源:https://stackoverflow.com/questions/49817446/is-object-guaranteed-to-be-initialized-before-calling-its-member-function