问题
Consider below program,
#include <iostream>
using namespace std;
class A
{
public:
A() { cout << "A constructor\n"; }
void f()
{
cout << "A used\n";
this->i++;
}
private:
int i;
};
class B
{
public:
B(A & a1)
{
cout << "B constructor\n";
a1.f();
}
};
class Z
{
public:
Z() : a_(), b_(a_) {}
private:
B b_;
A a_;
};
int main() {
Z z;
return 0;
}
Below is output it produces,
B constructor
A used
A constructor
My Question,
Since data member objects are created in order of their declaration in class, hence b_
will be created first. But how it is able to call a function on data member a_
which is still not created? Does compiler performs some kind of optimization to translate call to f()
to a plain function call? If yes, then how this->i++
is working?
回答1:
The compiler won't fight you when you explicitly instruct it to pass a reference to an uninitialized object somewhere. After all, the function you pass it to may be used to actually initialize the object.
However, accessing uninitialized data, e.g., your this->i++;
, results in undefined behavior.
来源:https://stackoverflow.com/questions/34011947/how-function-call-is-working-on-an-unitialized-data-member-object-in-constructor