问题描述
来自这个问题(仍然没有解决),我遇到了这个新问题,因此我在此举了一个例子:
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; }
};
在g ++ 6.3.0中,输出为:(g ++ -o test file1.cpp file2.cpp prac.cpp -std = c ++ 11)
密码
使用b
b ctor
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
因此从代码示例中看来,似乎没有这样的保证,并且可能是未定义的行为?标准中是否有关于此的任何说明?(我不认为这是重复的,因为这种情况有点不同:在a
的初始化中,调用b
的成员函数.)
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.)
推荐答案
否,不对无效对象调用任何非静态成员函数是您的工作,这包括但不限于将nullptr
作为this
传递,尚未创建的对象或已被破坏的对象.解决这种情况的方法之一是在函数中使用静态本地对象,而不是全局对象,然后将引用/指针返回给该函数.该方法仍然存在销毁顺序问题,但至少有一半问题消失了.
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.
这篇关于是否可以保证对象在调用其成员函数之前已初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!